Search notes:

Python: next()

Beware of None

The idiom while elem := next(itr) might not do what is expected if the list that is iterated over contains a None value:
lst = ['foo', 'bar', None, 'baz' ]

itr = iter(lst)

while elm := next(itr):
      print(elm)
Github repository about-Python, path: /builtin-functions/next/while-with-None.py
The while statement ends after bar is returned because None is considered to be False.
foo
bar

Skipping lines when reading a file

The following code snippet iterates over the lines in a file and prints them. However, the first line is skipped with the next() function:
#!/usr/bin/python3

#
#   Open a file for reading
#
f = open('file.txt')

#
#   Skip a line
#
next(f)

#
#   Print the remaining lines
#
for l in f:
    print(l, end='')
Github repository about-Python, path: /builtin-functions/next/open.py

See also

iterators

Index