-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenumerate object.py
More file actions
40 lines (32 loc) · 906 Bytes
/
enumerate object.py
File metadata and controls
40 lines (32 loc) · 906 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
names = ['Bob', 'Alice', 'Guido']
for index, value in enumerate(names, 1):
print(f'{index}: {value}')
'''
# HARMFUL: Don't do this
for i in range(len(my_items)):
print(i, my_items[i])
'''
# Create a list that can be enumerated
L = ['red', 'green', 'blue']
x = list(enumerate(L))
print(x)
# Prints [(0, 'red'), (1, 'green'), (2, 'blue')]
# Start counter from 10
L = ['red', 'green', 'blue']
x = list(enumerate(L, 10))
print(x)
# Prints [(10, 'red'), (11, 'green'), (12, 'blue')]
# When you iterate an enumerate object, you get a tuple containing (counter, item)
L = ['red', 'green', 'blue']
for pair in enumerate(L):
print(pair)
# Prints (0, 'red')
# Prints (1, 'green')
# Prints (2, 'blue')
# You can unpack the tuple into multiple variables as well.
L = ['red', 'green', 'blue']
for index, item in enumerate(L):
print(index, item)
# Prints 0 red
# Prints 1 green
# Prints 2 blue