Shorcuts & Tricks Flashcards

1
Q

Comprehensions

shortcuts

A
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 != ' '}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Ternary operator

shortcuts

A
condition = True
message = "Okay" if condition else "Not okay"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Lambda functions

shortcuts

A
adder = lambda x, y: x + y
print(adder(2, 3))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Using regex

shortcuts

A
import re
result = re.findall(r'\d+', 'hello 123 world 456')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Break, continue, and pass

shortcuts

A
for i in range(5):
    if i == 2:
        continue
    elif i == 4:
        break
    print(i)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

.apply()

shortcuts

A
df['a'] = df['a'].apply(lambda x:x**2)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Transpose

shortcuts

A
print(df.T)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

.rename

shortcuts

A
df = df.rename(columns={'a':'apple', 'b':'boy'})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

All/any

A

list1 = [True, True, False, True]
print(all(list1))
# False

list2 = [False, True, False]
print(any(list2))
# True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Emoji

A

from emoji import emojize
print(emojize(“:thumbs_up: Python is awesome! :thumbs_up:”))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Forward compatibility

A

from __future__ import division
print(5 / 2)
# 2.5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Get text from newspaper articles

A

!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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Consult Wikipedia

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

zip

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Generate unique identifier

A

Generate a random UUID

import uuid

id = uuid.uuid4()
# Print the UUID
print(id)
#6c81a22b-5839-48ec-9f2f-842d7b96c425

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

pprint

A

import pprint

data = {
‘name’: ‘John’,
‘age’: 30,
‘address’: {
‘street’: ‘Main St’,
‘city’: ‘New York’,
‘state’: ‘NY’
}
}
pprint.pprint(data)