Issue
What is the fastest and best way to get first value from list? There are multiple techniques, but what is the best (memory and speed) and why?
Examples below. I would be grateful for other techniques as well:
listis = [1, 2, 3, 4]
### 1:
###----------
value = next(iter(listis))
print(value)
### 2:
###----------
value = listis[0]
print(value)
### 3:
###----------
value, *args = listis
print(value)
Solution
value = listis[0]
is going to be unbeatable here as it’s just creating a new name (value
) referencing listis[0]
.
More importantly, it’s obvious what you actually mean. That makes life much better for the next person who looks at your code, who will likely be you.
Try:
import timeit
print(timeit.timeit("value = next(iter(listis))", setup="listis = [1, 2, 3, 4]", number=1_000_000))
print(timeit.timeit("value = listis[0]", setup="listis = [1, 2, 3, 4]", number=1_000_000))
print(timeit.timeit("value, *args = listis", setup="listis = [1, 2, 3, 4]", number=1_000_000))
This will show you that value = listis[0]
is the fastest.
0.0976
0.0264
0.1190
Answered By - Kirk Strauser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.