Skip to content

Instantly share code, notes, and snippets.

@usametov
Created November 5, 2020 16:12
Show Gist options
  • Select an option

  • Save usametov/9fe2119e8184db8f822cc48ddd64f22b to your computer and use it in GitHub Desktop.

Select an option

Save usametov/9fe2119e8184db8f822cc48ddd64f22b to your computer and use it in GitHub Desktop.
#replace for-loop, all iterables in Python can be used in a list comprehension.
full_name = "Yang Zhou"
characters = [char for char in full_name]
print(full_name)
print(characters)
# Yang Zhou
# ['Y', 'a', 'n', 'g', ' ', 'Z', 'h', 'o', 'u']
# using if condition -- filter analog
Genius = ["Yang", "Tom", "Jerry", "Jack", "tom", "yang"]
L1 = [name for name in Genius if name.startswith('Y')]
L2 = [name for name in Genius if name.startswith('Y') or len(name) < 4]
L3 = [name for name in Genius if len(name) < 4 and name.islower()]
print(L1, L2, L3)
# ['Yang'] ['Yang', 'Tom', 'tom'] ['tom']
# map example
Genius = ["Jerry", "Jack", "tom", "yang"]
L1 = [name.capitalize() for name in Genius]
print(L1)
# ['Jerry', 'Jack', 'Tom', 'Yang']
# another map example
Genius = ["Jerry", "Jack", "tom", "yang"]
L1 = [name if name.startswith('y') else 'Not Genius' for name in Genius]
print(L1)
# ['Not Genius', 'Not Genius', 'Not Genius', 'yang']
# use with ternary conditional
b = 2 if a > 0 else -1
# nested for-loop
Genius = ["Jerry", "Jack", "tom", "yang"]
L1 = [char for name in Genius for char in name]
print(L1)
# ['J', 'e', 'r', 'r', 'y', 'J', 'a', 'c', 'k', 't', 'o', 'm', 'y', 'a', 'n', 'g']
#another example
Genius = ["Jerry", "Jack", "tom", "yang"]
L1 = [char for name in Genius if len(name) < 4 for char in name]
print(L1)
# ['t', 'o', 'm']
# avoiding higher order functions for readability
L = map(func, iterable)
# can be replaced to:
L = [func(a) for a in iterable]
L = filter(condition_func, iterable)
# can be converted to
L = [a for a in iterable if condition]
# generator expression to reduce memory cost
large_list = [x for x in range(1_000_000)]
large_list_g = (x for x in range(1_000_000))
print(large_list.__sizeof__())
print(large_list_g.__sizeof__())
# 8697440
# 96
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment