If you are coming from php, you used to use "foreach" to iterate arrays or objects. This is used and some other languages too, such as JavavaScript for example. Foreach in python is a bit different.
list_with_fruits = ["grapes", "lime", "lemon", "cherry", "blueberry", "banana"]
Print the list before iterating(this is not mandatory)
print(list_with_fruits)
Now let's iterate through the list
print("iterating a basic list")
for fruit in list_with_fruits:
print(fruit)
If you want to gain access to the fruit index as well you can use the enumerate function to do it
print("iterating a list with index")
for index, fruit in enumerate(list_with_fruits):
print("index", index, "fruit", fruit)
multidimensional_list = [
["grapes", "lime", "lemon", "cherry", "blueberry", "banana"],
[ "Mercedes-Benz", "Toyota", "Volkswagen", "BMW", ],
["tiger", "lion", "elephant ", ]
]
for i, item in enumerate(multidimensional_list):
# separate each list with 50 *
print("*" * 50) # display 50 *
for j, name in enumerate(item):
print("Location: ", i,j, "Item Name: ", name)
So if you want to access fruits list you will have to do something like
print(multidimensional_list[0])
Then for the other one
print(multidimensional_list[1])
print(multidimensional_list[2])
This is what the first for is doing basically item is replacing multidimensional_list[0] with the item at first iteration then item = multidimensional_list[1] and so on
So now we know that item is a list, and you already know how to iterate a list
If you don't need an index on each fruit, cars, or animals, you could use the simple version without enumerate
for name in item:
print("Item Name: ", name)
In the same way you can iterate through a tuplet
list_with_fruits = ("grapes", "lime", "lemon", "cherry", "blueberry", "banana")
for fruit in list_with_fruits:
print(fruit)
same thing applies for index
for index, fruit in enumerate(list_with_fruits):
print("index", index, "fruit", fruit)
list_with_fruits = {"grapes": 30, "lime": 50, "lemon":60, "cherry":70, "blueberry":100, "banana":5}
If you use the same approach with dictionaries then only the key will be displayed
for fruit in list_with_fruits:
print(fruit)
Again if you use the same approach you used on the list, the index will be displayed instead of the value
for index, fruit in enumerate(list_with_fruits):
print(fruit, index)
So if you wanna display the key and the value use the items() method
for fruit, nr in list_with_fruits.items():
print( fruit, nr)
if the list is changing while you iterate you can create a copy of the list and delete from original list
list_with_fruits = ["grapes", "lime", "lemon", "cherry", "blueberry", "banana"]
for i, fruit in enumerate(list_with_fruits.copy()):
if fruit == 'lime':
del list_with_fruits[i]
print(list_with_fruits)
or you can create a new object while you iterate
list_with_fruits = ["grapes", "lime", "lemon", "cherry", "blueberry", "banana"]
new_fruit_list = []
for i, fruit in enumerate(list_with_fruits):
if fruit != 'lime':
new_fruit_list.append(list_with_fruits[i])
print(new_fruit_list)
Now let's convert our multidimensional list into a mix of tuplets, list and dicts
multidimensional_obj = {
"fruits": ["grapes", "lime", "lemon", "cherry", "blueberry", "banana"],
"cars": [ "Mercedes-Benz", "Toyota", "Volkswagen", "BMW" ],
"animals": ("tiger", "lion", "elephant " )
}
First let's iterate the dict
for key, items in multidimensional_obj.items():
print("*" * 50)
print("*", key)
for label in items:
print(f"*** {label}")
You can nest it on several levels but keep in mind that this nr is not limited
This limit applies to all other control flow blocks as well.
The limit for the number of nested control flow blocks is defined inside of code.h with a constant named CO_MAXBLOCKS.
If you have any questions feel free to contact me, I will update this tutorial if is the case