Python Base

Iterable

Are iterable : List, Dictionaries, Tuple, Set and Strings When using a dictionnary, there are several ways to iterate through the keys and values :

 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
41
user = {
  'name' : 'Garion',
  'age': 23,
  'can_run': True
}

# Iterate through Key Values
for item in user.items():
    print(item)

# Output key value pairs :
('name', 'Garion')
('age', 23)
('can_run', True)

# Iterate through Keys
for item in user.keys():
    print(item)

# Output Keys :
name
age
can_run

# Iterate through Values
for item in user.values():
    print(item)

# Output Values :
Garion
23
True

# Iterate trough key-values (common way)
for key, value in user.items():
    print(key, value)

# Output key value pairs :
name Garion
age 23
can_run True

Loop

The equivalent of for I=0; i<10; i++ can be obtained with the use of [range]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
for i in range(0, 10, 1): # Or for i in range( 10):
  print(i)


# Output : 
0
1
2
3
4
5
6
7
8
9

print(list(range(10)))

# output :
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

enumerate can be used to iterate through an iterable and returning an index.

1
2
3
4
5
6
7
8
for i,char in enumerate('Test'):
  print(i,char)

# output :
0 T
1 e
2 s
3 t