Advanced Python Flashcards

1
Q

\d

A

matches a digit (0-9)

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

?

A

matches 0 or 1 of previous character

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

+

A

matches 1 or more of previous character

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

*

A

Matchest any character 0 or more times

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

[]

A

matches any character inside of the brackets

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

Visualize tuple unpacking

A

you can use tuple unpacking
mylist = [(1,2),(3,4),(5,6),(7,8)]
for item in mylist:
print(item)

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

Visualize printing out the items of a dictionary

A

d = {‘k1’:1, ‘k2’:2,’K3’:3}
# for default you iterate through the keys
for item in d:
print(item)

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

What does this print?
d = {‘k1’:1, ‘k2’:2,’K3’:3}
for item in d.items():
print(item)

A

(‘k1’, 1)
(‘k2’, 2)
(‘K3’, 3)

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

What is the impact of continue?
for letter in mystring:
if letter == ‘a’:
continue #go back to the loop
print(letter)

A

It continues pass a, and prints the next characters
Smmy

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

Enumerate()

A

allows you to iterate over an iterable (like a list, string, or tuple) while keeping track of the index and value of each element.

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

What is the output?

words = [‘apple’, ‘banana’, ‘cherry’]
for index, value in enumerate(words):
print(f”Index: {index}, Value: {value}”)

A

Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: cherry

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

What is the output?

words = [‘apple’, ‘banana’, ‘cherry’]
indexed_words = list(enumerate(words))

print(indexed_words)

A

[(0, ‘apple’), (1, ‘banana’), (2, ‘cherry’)]

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

What is the output?

index_count = 0
for letter in “abcde”:
print(‘At index {} the letter is {}.’.format(index_count,letter))
index_count +=1

A

At index 0 the letter is a.
At index 1 the letter is b.
At index 2 the letter is c.
At index 3 the letter is d.
At index 4 the letter is e.

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

zip()

A

Combines multiple iterables (like lists, tuples, or strings) element-wise into pairs (tuples

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

What is the output of this?
names = [“Alice”, “Bob”, “Charlie”]
ages = [25, 30, 35]

zipped = zip(names, ages)
print(list(zipped))

A

[(‘Alice’, 25), (‘Bob’, 30), (‘Charlie’, 35)]

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

What is the output of this?
for name, age in zip(names, ages):
print(f”{name} is {age} years old.”)

A

Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.

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

How would you unzip this?
zipped_data = [(‘Alice’, 25), (‘Bob’, 30), (‘Charlie’, 35)]

A

names, ages = zip(*zipped_data)

print(list(names)) # [‘Alice’, ‘Bob’, ‘Charlie’]
print(list(ages)) # [25, 30, 35]

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

List Comprehensions

A

allow you to generate a new list by applying an expression to each item in an existing iterable (like a list, range, or tuple)

new_list = [expression for item in iterable if condition]

19
Q

Use a list comprehension to: Create a list of squares of numbers from 1 to 5.

A

squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]

20
Q

Use a list comprehension to generate a list of all combinations of numbers and letters:

A

combinations = [(x, y) for x in range(2) for y in ‘AB’]

21
Q

Use a function with tuple unpacking to increase the stock prices by 10 percent.
stock_prices = [(‘APPL’, 200), (‘GOOG’,400), (‘MSFT’, 100)]

A

for ticker,price in stock_prices:
print(price+(0.1*price))

22
Q

*args

A

args allows you to pass a tuple of parameters coming in.
arg is an arbitrary choice as long as followed by *.
But you should always use *args for style

23
Q

**kwargs

A

**kwargs returns a dictionary.

24
Q

Visualize how to use *args

A

def myfunc(*args): #the user can pass in as many arguments as wanted
return sum(args) * 0.05

myfunc(40,60,100,1,34)

25
Q

Visualize how to use **kwargs

A

def myfruit(**kwargs):
if ‘fruit’ in kwargs:
print(‘My fruit of choice is {}’.format(kwargs[‘fruit’]))
else:
print(“No fruit here”)
myfruit(fruit=’apple’, veggie=’lettuce’)

26
Q

Visualize how to use both *args and **kwargs

A

def use_both(*args,**kwargs): #this has to go in the order
print(args)
print(kwargs)
print(‘I would like {} {}’.format(args[0],kwargs[‘food’]))
use_both(10,20,30, fruit=’orange’,food=’eggs’)

27
Q

What are four general formulas for exponents?

A

r3 = r³
r
2 = r²
r0.5 = √r (square root)
r
-1 = 1/r (reciprocal)

28
Q

map()

A

Takes a function and an iterable (like a list).
Applies the function to each element in the iterable.
Returns a map object (convert it to a list using list()).

29
Q

Apply map to the below and tell the output:
numbers = [1, 2, 3, 4, 5]
# Using map() with a function
def square(x):
return x**2

A

squared = list(map(square, numbers))
print(squared)
Output:

[1, 4, 9, 16, 25]
Alternate is:
squared = list(map(lambda x: x**2, numbers))

30
Q

T or F: map() does not need a function to execute.

A

False. map() requires a function.
If you already have a function (def my_function()), you can just pass it to map().
If you don’t want to define a separate function, lambda lets you write a function inline for quick, one-time use.

31
Q

Use filter() to extract only even numbers from this list:
nums = [5, 10, 15, 20, 25, 30]

A

nums = [5, 10, 15, 20, 25, 30]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [10, 20, 30]

32
Q

Use map() to capitalize the first letter of each word:
fruits = [“mango”, “orange”, “peach”]

A

fruits = [“mango”, “orange”, “peach”]
capitalized = list(map(str.capitalize, fruits))
print(capitalized) # Output: [‘Mango’, ‘Orange’, ‘Peach’]

33
Q

filter()

A

Takes a function that returns True or False.
Filters the iterable, keeping only the elements where the function returns True.

34
Q

lambda: Anonymous Inline Functions

A

A small one-line function with no name (anonymous).
Used when you need a function just once (e.g., inside map() or filter()).

35
Q

Visualize using a lambda to add two numbers

A

add = lambda x, y: x + y
print(add(3, 5))

36
Q

Explain the LEGB Rule: Understanding Scope in Python

A

L - Local: Variables defined inside the current function.
E - Enclosing: Variables in the enclosing (outer) function, used in nested functions.
G - Global: Variables defined at the top level of a script or module.
B - Built-in: Names from Python’s built-in functions and libraries (like len, print, range).

37
Q

What are key concepts in Object Oriented Programming?

A

Classes → A blueprint for creating objects.
Objects → An instance of a class.
Attributes → Variables inside a class that store data.
Methods → Functions inside a class that operate on the object’s data.
self → Refers to the current instance of the class.
Encapsulation, Inheritance, Polymorphism, Abstraction → Advanced OOP concepts.

38
Q

what are class object attributes?

A

Class Object Attributes are defined outside of __init__().
All instances of the class share this attribute.
In this case, every Dog instance will have species = “mammal”.

39
Q

How do you create a class in python?

A

class Name():

40
Q

What is the method constructor?

A

__init__() is a constructor method that runs automatically when a new object is created.
self refers to the instance being created.
The attributes breed, name, and spots are passed as arguments.

41
Q

Why is the self keyword important to an object?

A

Passed inside the __init__() along with the class attributes, the self keyword is assigned to attributes.
The self keyword allows each instance to have its own unique values

42
Q

Visualize passing attributes to a class

A

def __init__(self, attr1, attr2, attr3)
self.attr1 = value
self.attr2 = value
self.attr3

43
Q

What are methods

A

Methods are functions inside a class that operate on instances.
self must always be the first parameter in instance methods.
any additional parameters do not.

44
Q

T or F: you must reference attributes and methods with self in a Class

A

False. you don’t need self for parameters because they exist only inside the method while it runs