Shorcuts & Tricks Flashcards
Comprehensions
shortcuts
squares = [x**2 for x in range(10)] squared_dict = {x: x**2 for x in range(10)} unique_set = {x for x in 'hello world' if x != ' '}
Ternary operator
shortcuts
condition = True message = "Okay" if condition else "Not okay"
Lambda functions
shortcuts
adder = lambda x, y: x + y print(adder(2, 3))
Using regex
shortcuts
import re result = re.findall(r'\d+', 'hello 123 world 456')
Break, continue, and pass
shortcuts
for i in range(5): if i == 2: continue elif i == 4: break print(i)
.apply()
shortcuts
df['a'] = df['a'].apply(lambda x:x**2)
Transpose
shortcuts
print(df.T)
.rename
shortcuts
df = df.rename(columns={'a':'apple', 'b':'boy'})
All/any
list1 = [True, True, False, True]
print(all(list1))
# False
list2 = [False, True, False]
print(any(list2))
# True
Emoji
from emoji import emojize
print(emojize(“:thumbs_up: Python is awesome! :thumbs_up:”))
Forward compatibility
from __future__ import division
print(5 / 2)
# 2.5
Get text from newspaper articles
!pip install newspaper3k
from newspaper import Article
url = “http://cnn.com/2023/03/29/entertainment/the-mandalorian-episode-5-recap/index.html”
article = Article(url)
article.download()
article.parse()
article.text
Consult Wikipedia
import wikipedia
# Search for a page
results = wikipedia.search(‘Python (programming language)’)
# Get the summary of the first result
summary = wikipedia.summary(results[0])
print(summary)
zip
list1 = [1, 2, 3]
list2 = [‘a’, ‘b’, ‘c’]
zipped = zip(list1, list2)
for i, j in zipped:
print(i, j)
#1 a
#2 b
#3 c
Generate unique identifier
Generate a random UUID
import uuid
id = uuid.uuid4()
# Print the UUID
print(id)
#6c81a22b-5839-48ec-9f2f-842d7b96c425