Python Flashcards

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
Q

explain all() and any() Functions

A

Check if any number is greater than 10

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”)

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
Q

sorted()
what is + example

A

Sorting in reverse order

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]

sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [4, 3, 2, 1]

27
Q

how to print a variable inside string in python?
f-strings (formatted string literals)

A

print(f”My name is {name} and I am {age} years old.”)

28
Q

replace() in strings

A

text = “Hello, world!”
new_text = text.replace(“world”, “Python”)
print(new_text) # Output: Hello, Python!

29
Q

split() in strings

A

text = “apple,banana,cherry”
fruits = text.split(“,”)
print(fruits) # Output: [‘apple’, ‘banana’, ‘cherry’]

30
Q

I have a string in a loop called new_word.
I need after iteration to remove the first letter from that string. How to?

A

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
Q

which is the issue?
for a, b in range(total_scores):

A

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
Q

how to control decimal spaces?
give an example
f-strings

A

print(f”{value:.2f}”)

print(f”{positive_count / total_len:.6f}”)

33
Q

this is not working okey…
min_list = arr
max_list = arr
why?

A

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
Q

difference of python 2 and 3.

A

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
Q

python key features

A

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
Q

The Global Interpreter Lock (GIL) is a mechanism used in CPython

A

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
Q

What are Python’s mutable and immutable data types?

A

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
Q

In Python, classes and objects are core concepts in Object-Oriented Programming (OOP).

A

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
Q

key difference between @staticmethod, @classmethod, and instance methods

A

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
Q

how is the constructor in python?

A

__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
Q

how to show in string output when objects gets created and printed

A

__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
Q

explain microservices

A

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
Q

creating and what is an API with cherrypy

A

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
Q
A