Python basics Flashcards

1
Q

What is a variable in Python?

A

A variable is a symbolic name that stores data in memory. It allows you to refer to the value later in the code.
Example:
x = 10
name = “Alice”

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

What are the main data types in Python?

A

the main data types include int (integer), float (decimal), str (string), bool (boolean), list, tuple, dict (dictionary), and set.

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

How do you comment code in Python?

A

Use # for single-line comments, and triple quotes ‘’’ or “”” for multi-line comments.
Example:
# This is a single-line comment
“””
This is a
multi-line comment
“””

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

What does type() do in Python?

A

type() returns the data type of a variable or value.
Example:
print(type(10)) # Output: <class ‘int’>

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

How do you create a list in Python?

A

A list is created using square brackets [] and can hold multiple data types.
Example:
fruits = [“apple”, “banana”, “cherry”]

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

What is the difference between a list and a tuple?

A

A list is mutable (changeable), while a tuple is immutable (cannot be changed after creation).
Example:
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

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

How do you access a dictionary value by key?

A

Use square brackets with the key name to access the corresponding value.
Example:
person = {“name”: “Alice”, “age”: 25}
print(person[“name”]) # Output: Alice

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

What is a set in Python?

A

A set is an unordered collection of unique elements.
Example:
my_set = {1, 2, 3, 3}
# Output: {1, 2, 3}

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

Explain an if statement in Python.

A

An if statement checks a condition and executes the code block if the condition is True.
Example:
x = 10
if x > 5:
print(“x is greater than 5”)

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

What is a for loop used for in Python?

A

A for loop iterates over a sequence (like a list, tuple, or string) and executes a code block for each element.
Example:
for fruit in [“apple”, “banana”, “cherry”]:
print(fruit)

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

What is the purpose of a while loop?

A

A while loop repeats a block of code as long as a specified condition is True.
Example:
count = 0
while count < 5:
print(count)
count += 1

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

How do you define a function in Python?

A

Use the def keyword followed by the function name and parentheses. Code inside the function is indented.
Example:
def greet(name):
print(“Hello, “ + name)

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

What is the purpose of the return statement in a function?

A

return exits the function and optionally returns a value to the caller.
Example:
def add(x, y):
return x + y

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

Explain the difference between local and global variables.

A

Local variables are defined within a function and cannot be accessed outside of it, while global variables are defined outside functions and can be accessed anywhere in the code.

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

What are list comprehensions?

A

List comprehensions provide a concise way to create lists based on existing iterables, often with conditions.
Example:
squares = [x**2 for x in range(10)]

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

what is the difference between yield and return

A

return
Exits the function immediately, returning a single value or object.
Memory Usage: Stores the entire result in memory, which can be inefficient for large data.
Example:

def get_numbers():
return [1, 2, 3, 4, 5]
yield
Pauses the function, saving its state, and returns a value temporarily.
Returns a generator: Allows handling one item at a time, ideal for large data.
Example:

def get_numbers():
for i in range(1, 6):
yield i
Summary
return: Exits the function with a single result.
yield: Pauses, returns items one by one, making it memory-efficient for large data.

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

What is a generator in Python?

A

A generator is a function that yields values one at a time and allows you to iterate through them without storing the entire sequence in memory.
Example:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1

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

How do you add an element to a list?

A

Use append() to add an element to the end, or insert(index, element) to add it at a specific position.
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.insert(1, 10) # [1, 10, 2, 3, 4]

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

How do you remove duplicates from a list?

A

Convert the list to a set and back to a list.
Example:
items = [1, 2, 2, 3]
unique_items = list(set(items)) # [1, 2, 3]

20
Q

What is a tuple, and how is it different from a list?

A

A tuple is an immutable, ordered sequence. Unlike lists, tuples cannot be modified after creation.

21
Q

How can you access elements in a tuple?

A

Use indexing, similar to lists.
Example:
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1

22
Q

How do you access a value in a dictionary?

A

Use the key in square brackets or the get() method.
Example:
person = {“name”: “Alice”}
print(person[“name”]) # Output: Alice

23
Q

How do you remove a key-value pair from a dictionary?

A

Use pop(key) or del statement.
Example:
person.pop(“age”)
del person[“name”]

24
Q

What is a set in Python?

A

An unordered collection of unique elements, defined with {}.

25
Q

How do you add elements to a set?

A

Use add() for a single element, or update() for multiple elements.
Example:
my_set = {1, 2}
my_set.add(3) # {1, 2, 3}
my_set.update([4, 5]) # {1, 2, 3, 4, 5}

26
Q

What is the difference between union() and intersection() methods in sets?

A

union() combines elements from both sets, while intersection() returns only common elements.

27
Q

How do you reverse a list in Python?

A

You can use the reverse() method (modifies the list in place) or slice notation.
lst = [1, 2, 3, 4]
lst.reverse() # In-place modification
# or
reversed_lst = lst[::-1] # Slicing

28
Q

How do you sort a list of tuples based on the second element in each tuple?

A

Use the sorted() function with a custom key.
Example:
data = [(1, ‘apple’), (3, ‘banana’), (2, ‘cherry’)]
sorted_data = sorted(data, key=lambda x: x[1]) # Sort by second element

29
Q

How do you concatenate two lists in Python?

A

Use the + operator or extend() method.
Example:
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2 # [1, 2, 3, 4]
# or
list1.extend(list2) # [1, 2, 3, 4]

30
Q

How do you merge two dictionaries in Python?

A

Use the update() method or dictionary unpacking (Python 3.5+).
Example:
dict1 = {“a”: 1, “b”: 2}
dict2 = {“c”: 3, “d”: 4}
dict1.update(dict2) # dict1 is now {“a”: 1, “b”: 2, “c”: 3, “d”: 4}
# or
merged_dict = {**dict1, **dict2} # Python 3.5+

31
Q

What happens when you use a mutable object (like a list) as a dictionary key?

A

It will raise a TypeError because dictionary keys must be immutable (hashable).
Example:
my_dict = {[“a”, “b”]: 1} # Raises TypeError: unhashable type: ‘list’

32
Q

How do you iterate over both keys and values in a dictionary?

A

Use items() to loop through key-value pairs.
Example:
my_dict = {“a”: 1, “b”: 2}
for key, value in my_dict.items():
print(key, value)

33
Q

How do you find the difference between two sets?

A

Use the difference() method or the - operator.
Example:
a = {1, 2, 3}
b = {2, 3, 4}
diff = a.difference(b) # {1}
# or
diff = a - b # {1}

34
Q

How do you find the symmetric difference between two sets?

A

Use symmetric_difference() or ^ operator to find elements in either set but not in both.
Example:
a = {1, 2, 3}
b = {3, 4, 5}
sym_diff = a.symmetric_difference(b) # {1, 2, 4, 5}
# or
sym_diff = a ^ b # {1, 2, 4, 5}

35
Q

What is the difference between shallow copy and deep copy?

A

A shallow copy duplicates the outer object, but references nested objects, while a deep copy duplicates both the outer and nested objects.
Example:
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

36
Q

How do you remove an item from a list by its index?

A

se the del statement or the pop() method.
Example:
lst = [1, 2, 3, 4]
del lst[2] # Removes element at index 2
lst.pop(1) # Removes element at index 1 and returns it

37
Q

How do you remove an element from a list by value, not index?

A

Use the remove() method to remove the first occurrence of a value.
Example:
lst = [1, 2, 3, 4]
lst.remove(3) # [1, 2, 4]

38
Q

What are list slicing and how do you use it to reverse a list?

A

List slicing allows you to access a range of elements in a list. To reverse a list, you use [::-1].
Example:
lst = [1, 2, 3]
reversed_lst = lst[::-1] # [3, 2, 1]

39
Q

How do you check if all elements in a list are unique?

A

Convert the list to a set and compare its length to the original list’s length.
Example:
lst = [1, 2, 3]
unique = len(lst) == len(set(lst)) # True

40
Q

How do you get a dictionary’s keys, values, and items?

A

Use keys(), values(), and items() methods.
Example:
my_dict = {“a”: 1, “b”: 2}
keys = my_dict.keys() # dict_keys([‘a’, ‘b’])
values = my_dict.values() # dict_values([1, 2])
items = my_dict.items() # dict_items([(‘a’, 1), (‘b’, 2)])

41
Q

How would you sort a dictionary by its values?

A

Use sorted() with a custom key function.
Example:
my_dict = {“a”: 3, “b”: 1, “c”: 2}
sorted_by_value = sorted(my_dict.items(), key=lambda x: x[1]) # [(‘b’, 1), (‘c’, 2),

42
Q

How do you find the intersection of two sets?

A

Use the intersection() method or the & operator.
Example:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1 & set2 # {2, 3}

43
Q

How can you check if a set is a subset of another set?

A

Use the issubset() method or the <= operator.
Example:
set1 = {1, 2}
set2 = {1, 2, 3}
print(set1.issubset(set2)) # True
print(set1 <= set2) # True

44
Q

What are the advantages of using a generator over a list?

A

enerators are memory-efficient because they yield values one at a time and don’t store the entire sequence in memory. They also allow for lazy evaluation, which means values are generated only when needed.
Example:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1

gen = count_up_to(5)
for num in gen:
print(num) # Outputs: 1, 2, 3, 4, 5

45
Q

What is the difference between deepcopy() and copy()?

A

Copy() performs a shallow copy, while deepcopy() creates a completely new object, including all nested objects.
Example:
import copy
obj = {“a”: [1, 2]}
shallow = copy.copy(obj)
deep = copy.deepcopy(obj)

46
Q
A