List Comprehensions for Data Scientists

Original article was published on Artificial Intelligence on Medium

List comprehension with a nested loop

Now that you have learned basic syntax and you know how to filter the list, we are going to learn how to use an additional loop. This will allow us to work with nested lists.

Yes, list comprehensions can handle nested lists by using nested loops!!!

Imagine that you have a list of lists:

nested_list = [[1,2], [3,4], [4,5]]

Now you want to take all elements out of it and put in a single list. This is called flattening a list.

flattened_list = [item for sublist in nested_list for item in sublist][1, 2, 3, 4, 4, 5]

Can you see how we nested the loops? The order is the same as with a traditional loop. Below there is the same code written with traditional for loop syntax:

flattened_list = []
for sublist in nested_list:
for item in sublist:
[1, 2, 3, 4, 4, 5]