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)
CodePudding user response:
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
CodePudding user response:
Calling the list element by its element number is always the fastest way. You aren't doing any calculation nor using any functions to get to it.
print(listis[0])
CodePudding user response:
listis[0]
This is the best choice in every case.
Python list
s were created to make their elements accessable by [i]
syntax.
For example this code...
listis[-1]
...will return the last element.
This code...
listis[::-1]
...will reverse the list
This code...
listis[2:]
...will return the list without the first two elements.
CodePudding user response:
We can compare these 3 ways:
Here the script:
import numpy as np
from matplotlib import pyplot as plt
from time import time
def nrml(lst):
value = lst[0]
def it(lst):
value = next(iter(lst))
def arg(lst):
value, *args = lst
def test():
res = []
for i in range(100, 100000, 100):
the_lst = [0] * i
nrml_s = time()
nrml(the_lst)
nrml_e = time()
it_s = time()
it(the_lst)
it_e = time()
arg_s = time()
arg(the_lst)
arg_e = time()
res.append(
[
i,
nrml_e - nrml_s,
it_e - it_s,
arg_e - arg_s
]
)
res = np.array(res)
plt.plot(res[:, 0], res[:, 1], label="Indexing")
plt.plot(res[:, 0], res[:, 2], label="Iter")
plt.plot(res[:, 0], res[:, 3], label="Unpack")
plt.legend()
plt.show()
if __name__ == '__main__':
test()
Please notice we did not check the memory usage. Just the time.
Here the result:
Please notice the Iter
and the Indexing
are close.