Skip to content

Instantly share code, notes, and snippets.

@radbrt
Last active February 6, 2020 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radbrt/8715b0a14381130f8242197abc40f603 to your computer and use it in GitHub Desktop.
Save radbrt/8715b0a14381130f8242197abc40f603 to your computer and use it in GitHub Desktop.
# A list of lists
ll = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
# flatten to single list
[n for li in ll for n in li]
# Corresponds to:
for li in ll:
for n in li:
print(n) # list2.append(n)
# Notice the order is the same in loops as in list comprehensions;
# First, iterate through list of lists (for li in ll), second, iterate through elements in list.
# The only difference is where the elements are returned.
# Flatten list but with conditions
[n for li in ll if len(li)<4 for n in li if n>3]
# Corresponds to
for li in ll:
if len(li)<4:
for n in li:
if n>3:
print(n)
# List of lists of lists
lll = [[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]], [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9, -10]]]
# flatten:
[n for ll in lll for li in ll for n in li]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment