Program Structure and Control Flow
Last updated
Last updated
The _
symbol is useful when the variable in that position is not important:
Use *var_name
to unpack multiple elements:
Output:
Let s
be an iterable, then enumerate(s)
creates an iterator that produces tuples (0, s[0])
, (1, s[1])
, (2, s[2])
, and so on:
Output:
for-else
LoopThe else
clause of a loop executes only if the loop runs to completion. This either occurs immediately (if the loop wouldn't execute at all) or after the last iteration. If the loop is terminated early using the break
statement, the else
clause is skipped.
An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for loop.
Lists, tuples, dictionaries, sets, strings, and file objects are all iterable objects. They are iterable containers which you can get an iterator from. All these objects have a iter()
method which is used to get an iterator: