Python Flashcards

(44 cards)

1
Q

append() + example

A

Adds an item to the end of the list.

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

pop() + example

A

Removes and returns an item at a specific index.

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

insert() + example

A

Inserts an item at a specific index.

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

remove() + example

A

Removes the first occurrence of a value.

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

count() + example

A

Counts occurrences of a specified value.

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

index() + example

A

Returns the index of the first occurrence of a value.

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

are list mutable in python?

A

Lists in Python are mutable, meaning they can be modified.

numbers = [1, 2, 3, 4, 5]
float_numbers = [1.1, 2.2, 3.3]
names = [“Alice”, “Bob”, “Charlie”]
names = [“Alice”, “Bob”, “Charlie”]

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

give me list of tuples

A

coordinates = [(1, 2), (3, 4), (5, 6)]

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

what is + example
int (Integer)

A

Definition: Represents whole numbers, positive or negative, without a decimal point.

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

what is + example
float (Floating-Point Number)

A

Definition: Represents real numbers with a decimal point.

x = 3.14 # Positive float
y = -2.71 # Negative float
z = 0.0 # Zero as a float

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

what is + example
matrix

A

Python does not have a built-in matrix type, but you can create matrices using nested lists or libraries like NumPy.

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

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

what is + example
tuple

A

Definition: An ordered, immutable collection of elements. Once created, a tuple cannot be modified.
Syntax: Defined using parentheses () or without them.

tuple1 = (1, 2, 3) # Tuple with integers
tuple2 = (“a”, “b”, “c”) # Tuple with strings
tuple3 = (1, “hello”, 3.14) # Mixed data types

Tuples are faster than lists.
Useful for data that should not change.

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

what is + example

dictionary

A

Definition: An unordered collection of key-value pairs.
Syntax: Defined using curly braces {} with keys and their corresponding values.

person = {
“name”: “Alice”,
“age”: 25,
“city”: “New York”
}

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

Convert int to float (function)

A

num_int = 5 # Integer
num_float = float(num_int) # Convert to float

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

Convert float to int (function)

A

num_float = 5.7 # Float
num_int = int(num_float) # Convert to integer

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

Convert int to str (function)

A

num_int = 123 # Integer
num_str = str(num_int) # Convert to string

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

Convert str to int (function)

A

num_str = “456” # String
num_int = int(num_str) # Convert to integer

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

Convert str to float (function)

A

num_str = “3.14” # String with decimals
num_float = float(num_str) # Convert to float

19
Q

Convert list to tuple and tuple to list (function)

A

Tuple to List

my_list = [1, 2, 3]
my_tuple = tuple(my_list)

my_tuple = (4, 5, 6)
my_list = list(my_tuple)

20
Q

for loop
iterate over list of strings and print those

A

fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)

21
Q

for loop
print numbers from 0-4

A

for i in range(5): # Iterates from 0 to 4
print(i)

22
Q

while loop.
when to use it?

A

The while loop repeatedly executes a block of code as long as a condition is True. It is useful when you do not know the number of iterations in advance.

23
Q

example of while loop with a counter

A

count = 0
while count < 5:
print(count)
count += 1 # Increment the counter

24
Q

explain break and continue

A

break Exits a loop prematurely. break
continue Skips the current iteration of a loop and moves to the next iteration. continue

25
explain all() and any() Functions
numbers = [2, 4, 6, 8] # Check if all numbers are even if all(num % 2 == 0 for num in numbers): print("All numbers are even") # Check if any number is greater than 10 if any(num > 10 for num in numbers): print("At least one number is greater than 10") else: print("No number is greater than 10")
26
sorted() what is + example
The sorted() function is used to return a new sorted list from the items in an iterable. numbers = [3, 1, 4, 2] sorted_numbers = sorted(numbers) print(sorted_numbers) # Output: [1, 2, 3, 4] # Sorting in reverse order sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers) # Output: [4, 3, 2, 1]
27
how to print a variable inside string in python? f-strings (formatted string literals)
print(f"My name is {name} and I am {age} years old.")
28
replace() in strings
text = "Hello, world!" new_text = text.replace("world", "Python") print(new_text) # Output: Hello, Python!
29
split() in strings
text = "apple,banana,cherry" fruits = text.split(",") print(fruits) # Output: ['apple', 'banana', 'cherry']
30
I have a string in a loop called new_word. I need after iteration to remove the first letter from that string. How to?
The [1:] syntax is a string slicing operation in Python. It creates a new string by excluding the first character of the original string and keeping the rest. new_word = new_word[1:]
31
which is the issue? for a, b in range(total_scores):
You're trying to unpack the result of range(total_scores) as if it provides two values (a and b), but range(total_scores) only produces integers, not pairs. Hence, Python raises the error TypeError: 'int' object is not iterable.
32
how to control decimal spaces? give an example f-strings
print(f"{value:.2f}") print(f"{positive_count / total_len:.6f}")
33
this is not working okey... min_list = arr max_list = arr why?
This does not create separate copies of the list. Both min_list and max_list still refer to the same list as arr. When you remove an element from min_list or max_list, it modifies arr as well. Solution: To prevent modifying the original list, you need to create copies of arr for min_list and max_list using the copy() method or list slicing.
34
difference of python 2 and 3.
Python 2 and Python 3 differ primarily in design and functionality: Print Statement: Python 2: print "Hello" Python 3: print("Hello") (requires parentheses). Python 2: No longer supported (end-of-life in 2020). Python 3: Actively developed and supported. Python 3 is the future and should be used for all new projects.
35
python key features
Simple and Readable Syntax: Python emphasizes readability, making it easy to learn and use. Dynamically Typed: Variables are not declared with a specific type; the type is determined at runtime. Interpreted Language: Python code is executed line by line by an interpreter, without the need for prior compilation. Versatile and Extensive Libraries: Python has a rich set of libraries and frameworks (e.g., NumPy, Pandas, Django). Object-Oriented and Functional: Supports multiple programming paradigms, including OOP and functional programming.
36
The Global Interpreter Lock (GIL) is a mechanism used in CPython
Memory management: The GIL simplifies memory management by preventing multiple threads from modifying objects at the same time. This means that even if a Python program has multiple threads, only one thread can run Python code at any given moment.
37
What are Python’s mutable and immutable data types?
Mutable Data Types: Lists: You can modify the elements of a list. python Dictionaries: You can add, modify, or remove key-value pairs. python Sets: You can add or remove elements from a set. python Immutable types: Strings, tuples, integers, floats, frozensets, etc. Tuples: You cannot change, add, or remove elements from a tuple. python tup = (1, 2, 3) tup[0] = 4 # Error: tuples are immutable
38
In Python, classes and objects are core concepts in Object-Oriented Programming (OOP).
Class A class is a blueprint or template for creating objects. It defines a set of attributes (variables) and methods (functions) that are common to all objects of that class. You can think of a class as a way to define a structure for objects. FORMULA_1_TEAM functions/methods resign_contract_with_Driver earn_a_point Object An object is an instance of a class. When you create an object from a class, you are essentially creating a specific instance of that class, with its own unique values for the attributes. FERRIRI MER
39
key difference between @staticmethod, @classmethod, and instance methods
Instance Methods Definition: These are the most common methods in Python classes. They require an instance (object) of the class to be called. obj = MyClass() obj.instance_method() @staticmethod Definition: A @staticmethod is a method that belongs to the class but does not require an instance or class reference to be called. class MyClass: @staticmethod def static_method(): print("This is a static method.") obj = MyClass() obj.static_method() Class method: Use when the method needs to modify or access class-level attributes and methods (e.g., factory methods). dosent have access on instance.
40
how is the constructor in python?
__init__(self, ...) (Constructor) Purpose: This method is called when an instance of a class is created. It is used to initialize the object's attributes.
41
how to show in string output when objects gets created and printed
__str__(self) (String Representation) Purpose: This method defines the "informal" or user-friendly string representation of an object. It is called when str() or print() is used on the object.
42
explain microservices
Microservices is an architectural style that structures an application as a collection of loosely coupled, independently deployable services. Each service is designed to perform a specific business function and is developed, deployed, and scaled independently. Microservices are often used in large-scale systems to improve flexibility, scalability, and maintainability. ej. 1. User Authentication Service: 2. products/content 3. notification service 4. payment 5. search service
43
creating and what is an API with cherrypy
CherryPy can be used to create an API in Python. CherryPy is a web framework that provides tools to build web applications, including APIs. It allows you to handle HTTP requests, define routes (or endpoints), and send HTTP responses.
44