Iterate over a List of Lists in Python

The following syntax can be used to iterate over a list of lists:

my_list = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]

for x in my_list:
for y in x:
print(y)

Example of iterating over a list of lists

Let’s suppose that you have a list of lists of colors.

You can then iterate over the list of lists using the syntax below:

colors_list = [
["blue", "green", "yellow"],
["black", "purple", "orange"],
["red", "white", "brown"],
]

for x in colors_list:
for y in x:
print(y)

Here is the result:

blue
green
yellow
black
purple
orange
red
white
brown

Let’s now add the string “_color” at the end of each item within the list of lists, and then save the results in a new flatten list called the new_colors_list:

colors_list = [
["blue", "green", "yellow"],
["black", "purple", "orange"],
["red", "white", "brown"],
]

new_colors_list = []

for x in colors_list:
for y in x:
new_colors_list.append(y + "_color")

print(new_colors_list)

As you can see, the string “_color” was added at the end of each item in the final list:

['blue_color', 'green_color', 'yellow_color', 
'black_color', 'purple_color', 'orange_color', 
'red_color', 'white_color', 'brown_color']

Optionally, you can use a list comprehension to achieve the same results:

colors_list = [
["blue", "green", "yellow"],
["black", "purple", "orange"],
["red", "white", "brown"],
]

new_colors_list = [(y + "_color") for x in colors_list for y in x]

print(new_colors_list)

The result:

['blue_color', 'green_color', 'yellow_color',
'black_color', 'purple_color', 'orange_color', 
'red_color', 'white_color', 'brown_color']

Leave a Comment