1. if...else...
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
following = l[i + 1] if i + 1 < len(l) else None
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
2. try...except...
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
try:
following = l[i + 1]
except IndexError:
following = None
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
3. dict
suitable for small list
l = [1, 2, 3, 4, 5]
dl = dict(enumerate(l))
for i, current in enumerate(l):
following = dl.get(i + 1)
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
4. List slicing
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
following = next(iter(l[i + 1:i + 2]), None)
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
5. itertools.zip_longest
from itertools import zip_longest
l = [1, 2, 3, 4, 5]
for i, (current, following) in enumerate(zip_longest(l, l[1:])):
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
Using Jupyter magic command of %%timeit
init
from itertools import zip_longest
l = list(range(10000000))
Result
Method |
Consume |
if...else... |
2.62 s |
try...except... |
1.14 s |
dict |
2.61 s |
List slicing |
3.75 s |
itertools.zip_longest |
1.14 s |