![]() |
|
[Tut] For Loop with Two Variables (for i j in python) - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] For Loop with Two Variables (for i j in python) (/thread-99764.html) |
[Tut] For Loop with Two Variables (for i j in python) - xSicKxBot - 08-03-2022 For Loop with Two Variables (for i j in python) 5/5 – (1 vote) for i j in python The Python expression Code: for i, j in XXXCode: XXXCode: iCode: jHere’s an example: Code: for i, j in [('Alice', 18), ('Bob', 22)]: print(i, 'is', j, 'years old')Output: Code: Alice is 18 years old
Bob is 22 years oldNotice how the first loop iteration captures Code: i='Alice'Code: j=18Code: i='Bob'Code: j=22for i j in enumerate python The Python expression Code: for i, j in enumerate(iterable)Code: iCode: jHere’s an example where we assign the counter values Code: i=0,1,2Code: lstCode: lst = ['Alice', 'Bob', 'Carl']
for i, j in enumerate(lst): print(i, j)Output: Code: 0 Alice
1 Bob
2 CarlNotice how the loop iteration capture:
Learn More: The Code: enumerate()![]() for i j in zip python The Python expression Code: for i, j in zip(iter_1, iter_2)Code: iter_1Code: iter_2Code: iCode: jHere’s an example that zips together the two lists Code: [1,2,3]Code: [9,8,7,6,5]Code: for i, j in zip([1,2,3], [9,8,7,6,5]): print(i, j)Output: Code: 1 9
2 8
3 7 Learn More: The Code: zip()![]() for i j in list python The Python expression Code: for i, j in listCode: iCode: jHere’s an example: Code: for i, j in [(1,9), (2,8), (3,7)]: print(i, j)Output: Code: 1 9
2 8
3 7The Python expression Code: for i, j, k in iterableCode: iCode: jHere’s an example: Code: for i, j, k in [(1,2,3), (4,5,6), (7,8,9)]: print(i, j, k)Output: Code: 1 2 3
4 5 6
7 8 9Given two lists Code: aCode: bCode: for i,j in zip(a,b)Given one list Code: ['a', 'b']Code: for i,j in enumerate(['a', 'b'])Summary The Python Code: forCode: zip()Code: enumerate()Code: for i, j in zip(range(10), range(10)): # (0,0), (1,1), ..., (9,9)If a list element is an iterable by itself, you can capture all iterable elements using a comma-separated list when defining the loop variables. Code: for i,j,k in [(1,2,3), (4,5,6)]: # Do Something |