Reputation: 121
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
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:
item
, is what will contain the returned list.for sublist in nested_list
so first you iterate over the each element in your input list and name it sublist
.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