Skip to content

Instantly share code, notes, and snippets.

@leveled
Created February 22, 2021 00:26
Show Gist options
  • Save leveled/d1a57380c10daa1fefdfbc5b1eff3e0d to your computer and use it in GitHub Desktop.
Save leveled/d1a57380c10daa1fefdfbc5b1eff3e0d to your computer and use it in GitHub Desktop.
List comprehensions in Python cheatsheet
#Basic format
[thing for thing in list of things]
#Basic list comprehension with if statement
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
fish_list = [fish for fish in fish_tuple if fish != 'octopus']
#Nested if statements
number_list = [x for x in range(100) if x % 3 == 0 if x % 5 == 0]
#Nested for statements
my_list = [x * y for x in [20, 40, 60] for y in [2, 4, 6]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment