For Loops
Iterating with for loops
Interview Relevant: Essential for iteration
For Loops
Iterate over sequences and iterables.
Code Examples
For loop patterns in Python.
python
1# Iterate over list
2for item in [1, 2, 3]:
3 print(item)
4
5# Iterate with index
6for i, item in enumerate([1, 2, 3]):
7 print(i, item)
8
9# Range
10for i in range(5): # 0, 1, 2, 3, 4
11 print(i)
12for i in range(2, 5): # 2, 3, 4
13 print(i)
14for i in range(0, 10, 2): # 0, 2, 4, 6, 8
15 print(i)
16
17# Iterate over string
18for char in "hello":
19 print(char)
20
21# Iterate over dict
22for key in {"a": 1, "b": 2}:
23 print(key)
24for key, value in {"a": 1}.items():
25 print(key, value)
26
27# zip - parallel iteration
28for a, b in zip([1, 2], ['a', 'b']):
29 print(a, b)