Python next - How to iterate and get the next item of a list

Python next returns the next item of an iterator. But what's an iterator? Python iterator is similar to list and can be iterated.

a = iter([1, 2, 3])

print(a)  # <list_iterator object at 0x102940cd0>
print(type(a))  # <class 'list_iterator'>

print(next(a))  # 1
print(next(a))  # 2
print(next(a))  # 3
print(next(a))  # StopIteration

a is not list but list_iterator. The first next(a) is 1, and the second is 2, ... so "inner index" increases every time calling next function.

The 4th next(a) raises the error because a has only 3 items.

Note

Python list_iterator can be iterated in for loop.

a = iter([1, 2, 3])

for i in a:
    print(i)

# 1
# 2
# 3

Python Tips

Python Tutorial