C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Unpack: We can unpack the tuple directly in the for-loop clause. Or we can receive the tuple and access its items later.
Python program that uses enumerate
animals = ["cat", "bird", "dog"]
# Use enumerate to get indexes and elements from an iterable.
# ... This unpacks a tuple.
for i, element in enumerate(animals):
print(i, element)
# Does not unpack the tuple.
for x in enumerate(animals):
print(x, "UNPACKED =", x[0], x[1])
Output
0 cat
1 bird
2 dog
(0, 'cat') UNPACKED = 0 cat
(1, 'bird') UNPACKED = 1 bird
(2, 'dog') UNPACKED = 2 dog
Python program that enumerates over string
word = "one"
# Enumerate over a string.
# ... This is a good way to get indexes and chars from a string.
for i, value in enumerate(word):
print(i, value)
Output
0 o
1 n
2 e
Pass: We use the pass statement to indicate an empty loop. Enumerate() fails, so this is not reached.
passPython program that causes not iterable error
number = 10
# We cannot enumerate an object that is not iterable.
for i, value in enumerate(number):
pass
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 7, in <module>
for i, value in enumerate(number):
TypeError: 'int' object is not iterable