Skip to content

Instantly share code, notes, and snippets.

@joyadauche
Last active February 29, 2020 16:58
Show Gist options
  • Save joyadauche/a1439680926c4066a1bd4975306a4a74 to your computer and use it in GitHub Desktop.
Save joyadauche/a1439680926c4066a1bd4975306a4a74 to your computer and use it in GitHub Desktop.
The Proficient Pythonista: List Comprehensions
numbers = [2, 9, 1, 4, 0]
new_numbers = []
for number in numbers:
new_numbers.append(number + 3)
print(new_numbers)
[[i*j for j in range(1, 3)] for i in range(5, 8)]
# output =>
# [[5, 10],
# [6, 12],
# [7, 14]]
# to flatten the list:
[i*j for i in range(5, 8) for j in range(1, 3)]
# output => [5, 10, 6, 12, 7, 14]
matrix = [
[7, 7, 7],
[8, 8, 8],
[9, 9, 9],
]
flattened = [num for row in matrix for num in row]
print(flattened)
# output => [7, 7, 7, 8, 8, 8, 9, 9, 9]
numbers = [2, 9, 1, 4, 0]
[number + 3 for number in numbers]
[number for number in range(10)]
flash_tuple = ('the flash', 'kid flash', 'reverse flash', 'cisco')
flash_list = [flash for flash in flash_tuple if flash != 'cisco']
print(flash_list)
numbers = [num for num in range(20) if num % 2 == 0 if num % 4 == 0]
print(numbers)
super_heros = ['blackpanther', 'aquaman', 'wonderwoman', 'ironman', 'antman', 'superman', 'xmen', 'powerrangers']
filtered_heros = [hero if len(hero)>=8 else '' for hero in super_heros]
print(filtered_heros)
cool_quote = "excellence gives room for growth"
unique_letters = {character for character in cool_quote if character in 'aeiou'}
print(unique_letters)
# output => {'o', 'e', 'i'}
super_heros = ['blackpanther', 'antman', 'superman', 'xmen', 'powerrangers']
new_heros = {hero: len(hero) for hero in super_heros}
print(new_heros)
# output => {'blackpanther': 12, 'antman': 6, 'superman': 8, 'xmen': 4, 'powerrangers': 12}
for i in range(5, 8):
for j in range(1, 3):
print(f"{i}*{j}={i * j}")
# f is a formatted string literal and it is new in python 3.6 - they are expressions evaluated at run time
# output =>
# 5*1=5
# 5*2=10
# 6*1=6
# 6*2=12
# 7*1=7
# 7*2=14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment