Idiomatic Python Flashcards
x = y = z = 10
x = 11
Whats the value of y, z now?
its still 10
How to swap values a and b
(a,b) = (b,a)
concatenate_this_list = [“FistString”, “SecondString”, “ThirdString”]
concatenated_string = ‘ ‘.join(concatenate_this_list)
print (concatenated_string)
’ ‘ leaves space between list elements so the result is
FirstString SecondString ThirdString
Whats the pythonic way of this:
x=y=z=10
if x<=y and y<=z:
print (“All equal”)
if x<=y<=z
Whats the pythonic way of this?
if name == “Tom” or name == “Nick” or name == “Harry”:
is_generic_name = True
is_generic_name = name in [“Tom”, “Nick”, “Harry”]
Empty squences like (), [], {} are falsy?
Yes
None is falsy?
Yes
Numeric 0 and emtpy strings are falsy?
yes
Whats the pythonic for this?
colors = [“red”, “green”, “blue”, “yellow”]
for i in range(len(colors)-1, -1, -1):
print (colors[i])
for color in reversed(colors)
Output?
fruits = [“strawberry”, “watermelon”, “banana”]
colors = [“red”, “green”, “yellow”, “blue”]
for fruit, color in zip(fruits, colors):
print (f”{fruit} –> {color}”)
strawberry –> red
watermelon –> green
banana –> yellow
original_list = range(4, -4, -1)
has_some_positive = any(element >0 for element in original_list)
True
fruit_colors = {“watermelon”: “green”, “strawberry”: “red”, “banana”: “yellow”}
for fruit, color in fruit_colors.items():
print (f”Fruit: {fruit} is {color}”)
.keys if u dont care about the values
.items if you care both about the keys and values
fruits = [“strawberry”, “watermelon”, “banana”]
colors = [“red”, “green”, “yellow”]
fruit_colors = dict(zip(fruits, colors))
print (fruit_colors)
Creates a dict out of lists
person_name = {“first_name”: “Nikos”, “surname”: “Giatrakos”}
person_characteristics = {“age”: 40, “height”: 1.85}
person = {**person_name, **person_characteristics}
person
merge dictionaries
Pythonic of :
def check_generic_name(name):
if name in [“Tom”, “Nick”, “Harry”]:
return name
return “Not included”
print (check_generic_name(“Nick”))
def check_generic_name(name):
return name if name in [“Tom”, “Nick”, “Harry”] else “Not included”
print (check_generic_name(“Nikos”))