On Tue, Oct 5, 2021 at 9:46 AM Erik Demaine <edema...@mit.edu> wrote:
> Of course, the universal way to get the
> first item from an iterable x is
>
> item = next(iter(x))
>
> I can't say this is particularly readable, but it is functional and fast.

I think we can add `itertools.first()` for this idiom, and
`itertools.last()` for `next(iter(reversed(x)))` idiom.

>
> Given the dictionary order guarantee from Python 3.7, adding indexing
> (__getitem__) to dict views seems natural.  The potential catch is that (I
> think) it would require linear time to access an item in the middle, because
> you need to count the dummy elements.  But accessing [i] and [-i] should be
> doable in O(|i|) time.

It is not true. They are O(n) where n is the maximum dict size.

>
> Python is also full of operations that take linear time to do: list.insert(0,
> x), list.pop(0), list.index(), etc.  But it may be that __getitem__ takes
> constant time on all built-in data structures, and the apparent symmetry but
> very different performance between dict()[i] and list()[i] might be confusing.
> That said, I really just want d[0] and d[-1], which is when these are fast.

They are not first. Since `next(iter(d))` is O(n), following code is O(n^2)

```
while d:
    del d[next(iter(d))]
```

Making list is much faster than it. Following code is O(n).

```
for k in list(d):
    del d[k]
```

>
> I found some related discussion in
> https://mail.python.org/archives/list/python-ideas@python.org/thread/QVTGZD6USSC34D4IJG76UPKZRXBBB4MM/
> but not this exact idea.

What is difference between your idea and previsous discussion?


-- 
Inada Naoki  <songofaca...@gmail.com>
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/PHJONYONXXJ5Y6Z76NIORHLC2C6WKH6U/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to