Python Understanding basics of for loop

eye-catch Python

for loop is one of the important techniques that every programmer needs to master in the early stage.

Sponsored links

How to use for-in

Let’s see the first example.

for num in [22, 33, 44, 55]:
    print(num)
# 22
# 33
# 44
# 55

The right side is a list that is iterable. I declare num variable that can be used in the loop body. The value in the list is assigned to num variable.

You can also add else keyword if you want to add post-process.

for num in [22, 33, 44, 55]:
    print(num)
else:
    print(f"Last number is {num}")
# 22
# 33
# 44
# 55
# Last number is 55

num variable can also be used in the else clause.

However, I don’t see any merits to use else. It just increases a line. If you want to do something after the loop, just write the code after the for-in loop.

Sponsored links

for-in for a string value

If for-in is used for a string value, the string can be processed one character by one character.

for char in "Hello":
    print(char)
# H
# e
# l
# l
# o

for-in for tuple

for-in can be used for tuple too.

for element in ([1, 2, 3], "Hello", 5, ("key", "value")):
    print(element)
# [1, 2, 3]
# Hello
# 5
# ('key', 'value')

Use range function for simple loop

If you just want to loop x times, you implement it in the following way in JavaScript.

for(let i = 0; i < 5; i++){
  console.log(i);
}

In Python, you can use range function instead.

for num in range(5):
    print(num)
# 0
# 1
# 2
# 3
# 4

You can control the start/end number as well as the step.

print(list(range(5, 15)))
# [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(list(range(5, 15, 2)))
# [5, 7, 9, 11, 13]

Generate a new list

Python has a unique syntax. The following two codes come to the same result.

for num in range(5):
    print(num)

[print(num) for num in range(5)]

It is nice if you want to generate a new list from it.

new_list = [num * num for num in range(5)]
print(new_list)
# [0, 1, 4, 9, 16]

You can easily create a new list on a single line. But it is not good that IntelliSense’s autocomplete doesn’t work in this case while typing because the variable name is defined later.

It would be nice if the following syntax is allowed… but actually not.

# NOT WORK
new_list = [for num in range(5): num * num]

If you use this syntax, you can add a new line wherever you want. All the following codes work as expected.

[
    print(num * num) for 
    num
    in
    range(5)
]
[
    print(num * num)
    for num
    in range(5)
]
[
    print(num * num)
    for num
    in
    range(5)
]

Let’s check whether it’s really a different instance or not.

lower_cases = ["a", "b", "c"]
lower_cases2 = [c for c in lower_cases]
print(lower_cases is lower_cases)   # True
print(lower_cases is lower_cases2)  # False
print(lower_cases == lower_cases2)  # True

is keyword can be used if you want to check if the two objects are exactly the same object. The result is different even though the elements are the same.

for-in loop for list of list

Let’s check how it behaves if the element of a list is list.

array = [[1, 11], [2, 22], [3, 33]]
for i, k in array:
    print(f"i: {i}, k: {k}")
# i: 1, k: 11
# i: 2, k: 22
# i: 3, k: 33

Multiple variables can be declared between for and in keywords. The first argument corresponds to the first element of the list.

But you don’t have to do that if you prefer the following way.

array = [[1, 11], [2, 22], [3, 33]]
for key_value in array:
    print(f"i: {key_value[0]}, k: {key_value[1]}")

Since the element of the list is list, you can simply use it as a normal list.

How to get element index

If you want to use the index number of the element, you need to call enumerate function.

array = [[1, 11], [2, 22], [3, 33]]
for i, [key, value] in enumerate(array):
    print(f"i: {i}, [{key}, {value}]")
# i: 0, [1, 11]
# i: 1, [2, 22]
# i: 2, [3, 33]

You need to use brackets if you want to prepare different variables for the elements of the list.

Comments

Copied title and URL