Advanced Python Flashcards
\d
matches a digit (0-9)
?
matches 0 or 1 of previous character
+
matches 1 or more of previous character
*
Matchest any character 0 or more times
[]
matches any character inside of the brackets
Visualize tuple unpacking
you can use tuple unpacking
mylist = [(1,2),(3,4),(5,6),(7,8)]
for item in mylist:
print(item)
Visualize printing out the items of a dictionary
d = {‘k1’:1, ‘k2’:2,’K3’:3}
# for default you iterate through the keys
for item in d:
print(item)
What does this print?
d = {‘k1’:1, ‘k2’:2,’K3’:3}
for item in d.items():
print(item)
(‘k1’, 1)
(‘k2’, 2)
(‘K3’, 3)
What is the impact of continue?
for letter in mystring:
if letter == ‘a’:
continue #go back to the loop
print(letter)
It continues pass a, and prints the next characters
Smmy
Enumerate()
allows you to iterate over an iterable (like a list, string, or tuple) while keeping track of the index and value of each element.
What is the output?
words = [‘apple’, ‘banana’, ‘cherry’]
for index, value in enumerate(words):
print(f”Index: {index}, Value: {value}”)
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: cherry
What is the output?
words = [‘apple’, ‘banana’, ‘cherry’]
indexed_words = list(enumerate(words))
print(indexed_words)
[(0, ‘apple’), (1, ‘banana’), (2, ‘cherry’)]
What is the output?
index_count = 0
for letter in “abcde”:
print(‘At index {} the letter is {}.’.format(index_count,letter))
index_count +=1
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.
zip()
Combines multiple iterables (like lists, tuples, or strings) element-wise into pairs (tuples
What is the output of this?
names = [“Alice”, “Bob”, “Charlie”]
ages = [25, 30, 35]
zipped = zip(names, ages)
print(list(zipped))
[(‘Alice’, 25), (‘Bob’, 30), (‘Charlie’, 35)]
What is the output of this?
for name, age in zip(names, ages):
print(f”{name} is {age} years old.”)
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
How would you unzip this?
zipped_data = [(‘Alice’, 25), (‘Bob’, 30), (‘Charlie’, 35)]
names, ages = zip(*zipped_data)
print(list(names)) # [‘Alice’, ‘Bob’, ‘Charlie’]
print(list(ages)) # [25, 30, 35]
List Comprehensions
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]
Use a list comprehension to: Create a list of squares of numbers from 1 to 5.
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
Use a list comprehension to generate a list of all combinations of numbers and letters:
combinations = [(x, y) for x in range(2) for y in ‘AB’]
Use a function with tuple unpacking to increase the stock prices by 10 percent.
stock_prices = [(‘APPL’, 200), (‘GOOG’,400), (‘MSFT’, 100)]
for ticker,price in stock_prices:
print(price+(0.1*price))
*args
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
**kwargs
**kwargs returns a dictionary.
Visualize how to use *args
def myfunc(*args): #the user can pass in as many arguments as wanted
return sum(args) * 0.05
myfunc(40,60,100,1,34)
Visualize how to use **kwargs
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’)
Visualize how to use both *args and **kwargs
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’)
What are four general formulas for exponents?
r3 = r³
r2 = r²
r0.5 = √r (square root)
r-1 = 1/r (reciprocal)
map()
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()).
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
squared = list(map(square, numbers))
print(squared)
Output:
[1, 4, 9, 16, 25]
Alternate is:
squared = list(map(lambda x: x**2, numbers))
T or F: map() does not need a function to execute.
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.
Use filter() to extract only even numbers from this list:
nums = [5, 10, 15, 20, 25, 30]
nums = [5, 10, 15, 20, 25, 30]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [10, 20, 30]
Use map() to capitalize the first letter of each word:
fruits = [“mango”, “orange”, “peach”]
fruits = [“mango”, “orange”, “peach”]
capitalized = list(map(str.capitalize, fruits))
print(capitalized) # Output: [‘Mango’, ‘Orange’, ‘Peach’]
filter()
Takes a function that returns True or False.
Filters the iterable, keeping only the elements where the function returns True.
lambda: Anonymous Inline Functions
A small one-line function with no name (anonymous).
Used when you need a function just once (e.g., inside map() or filter()).
Visualize using a lambda to add two numbers
add = lambda x, y: x + y
print(add(3, 5))
Explain the LEGB Rule: Understanding Scope in Python
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).
What are key concepts in Object Oriented Programming?
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.
what are class object attributes?
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”.
How do you create a class in python?
class Name():
What is the method constructor?
__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.
Why is the self keyword important to an object?
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
Visualize passing attributes to a class
def __init__(self, attr1, attr2, attr3)
self.attr1 = value
self.attr2 = value
self.attr3
What are methods
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.
T or F: you must reference attributes and methods with self in a Class
False. you don’t need self for parameters because they exist only inside the method while it runs