Reputation: 537
I'm quite new to Python, and was wondering how I flatten the following nested list using list comprehension, and also use conditional logic.
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
The following returns a nested list, but when I try to flatten the list by removing the inner square brackets I get errors.
odds_evens = [['odd' if n % 2 != 0 else 'even' for n in l] for l in nested_list]
Upvotes: 3
Views: 1009
Reputation: 1
What is wrong here ?
>>> nested_list = [[1,2,3], [4,5,6], [7,8,9]]
>>> odds_evens = ['odd' if n % 2 != 0 else 'even' for 1 in nested_list for n in 1]
File "<stdin>", line 1
SyntaxError: can't assign to literal
Upvotes: 0
Reputation: 88
Read data from Nested list and output to a Flat list based on condition
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
flat_list = [item for sublist in nested_list for item in sublist]
# >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
flat_list_even = [item for sublist in nested_list for item in sublist if item % 2 == 0]
# >>> [2, 4, 6, 8]
flat_list_odd = [item for sublist in nested_list for item in sublist if item % 2 != 0]
# >>> [1, 3, 5, 7, 9]
flat_list_literal = ["even" if item % 2 == 0 else "odd" for sublist in nested_list for item in sublist]
# >>> ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Upvotes: 0
Reputation: 1238
To create a flat list, you need to have one set of brackets in comprehension code. Try the below code:
odds_evens = ['odd' if n%2!=0 else 'even' for n in l for l in nested_list]
Output:
['odd', 'odd', 'odd', 'even', 'even', 'even', 'odd', 'odd', 'odd']
Upvotes: -1
Reputation: 82765
Your syntax was a little wrong. Try below snippet.
nested_list = [[1,2,3], [4,5,6], [7,8,9]]
odds_evens = ['odd' if n % 2 != 0 else 'even' for l in nested_list for n in l]
print(odds_evens)
Output:
['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
Upvotes: 6