4

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'.

Gabio
  • 9,126
  • 3
  • 12
  • 32
Coding Grind
  • 111
  • 6

1 Answers1

3

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.
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • Hi thank you for that answer, it worked! I'm not sure about something though, why do that work and the more logical approach doesn't: `[item for item in sublist for sublist in nested_list]` where can I learn more about it as well (syntax). – Coding Grind May 01 '20 at 13:02
  • @CodingGrind: The loops read from left to right, with the leftmost loop being the "outer" loop, and the rightmost the most "inner" loop. Your proposed approach doesn't work because `sublist` doesn't exist until the "outer" loop has looped once. Read [the functional programming howto](https://docs.python.org/3/howto/functional.html?highlight=list%20comprehension#generator-expressions-and-list-comprehensions) for more. – ShadowRanger May 01 '20 at 13:08
  • @CodingGrind I've added an explanation, does it make sense for you? – Gabio May 01 '20 at 13:18
  • @ShadowRanger tell me if I understood incorrectly, but in list comprehensions python reads the any for loops that it contains, and then it checks if and else and what to store for it? – Coding Grind May 01 '20 at 14:05
  • @CodingGrind: There is no `else` in list comprehension syntax (if you see one, it's part of a ternary conditional expression embedded in the listcomp, but it's not part of listcomp special behaviors). As for checking `if`s, that's ordered the same way as the `for`s (so `if` that are further left are checked less frequently, and control the inner loops). – ShadowRanger May 01 '20 at 14:09