In this article we will discuss a faster and more efficient way to get only the first item from a view object in Python.
In a program I was using the following code to get the first key from a
via a view object.
firstkey = list(data.keys())
dict in question has about 67000 items in it, this takes
a significant amount of time.
In : %timeit list(data.keys()) 745 µs ± 2.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Also, the intermediate list is quite big.
In : import sys In : sys.getsizeof(list(data.keys())) Out: 536440
That’s 523 KiB allocated to get one number. There has to be a better way.
We use a combination of
firstkey = next(iter(data.keys()))
Not only is this significantly faster.
In : %timeit next(iter(data.keys())) 140 ns ± 0.0378 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
It also uses much less memory.
In : sys.getsizeof(iter(data.keys())) Out: 72
As a bonus, this also works for the last element in the view using
reversed() instead of
In : next(iter(data.keys())) Out: 5 In : next(reversed(data.keys())) Out: 67052
For comments, please send me an e-mail.
- From python script to executable with cython
- On Python speed
- Python 3.11 speed comparison with 3.9
- Python & standard output redirection on ms-windows
- Profiling Python scripts (5): ent_without_numpy