Coding Grind
Coding Grind

Reputation: 121

How to use a list comprehension to store the nested list of a list

I was wondering, if I had nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] how would I be able to break the loop and only storing the items in each of the nested lists, what I mean by loop is that when I try:

result = [[value_1 for value_1 in a_list] for a_list in nested_list]

The only thing result will have is...well the exact list we started with :/. So what would be a way of storing the items like this [1, 2, 3, 4, 5, 6, 7, 8, 9] using a list comprehension on nested_list. I repeat, a list comprehension, not a 'for loop'.

Upvotes: 4

Views: 1044

Answers (1)

Gabio
Gabio

Reputation: 9504

try this:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output = [item for sublist in nested_list for item in sublist]
print(output) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation:

When you use list comprehension for nested loops, the structure of the expression is as follows:

  • The leftmost expression, item, is what will contain the returned list.
  • The first loop from left is the most outer loop, for sublist in nested_list so first you iterate over the each element in your input list and name it sublist.
  • The right most loop, for item in sublist is the most inner loop. In your case this loops iterates over each element of the sublist and name it item which will eventually will be returned in the output.

Upvotes: 3

Related Questions