List Flatten in Python
Level 3111 keystrokes
This flattens a nested list using list comprehension. The double for loop iterates through sublists and their items.
Python code
# A list of three sublists1nested = [[1, 2], [3, 4], [5, 6]]# The for clauses run left to right, like nested loops: for each sublist, for each item# Every item goes into one flat list2flattened = [item for sublist in nested for item in sublist]# Prints [1, 2, 3, 4, 5, 6]3print(flattened)Output
[1, 2, 3, 4, 5, 6]
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
,× 5[× 5]× 5=× 2(× 1)× 1