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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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”]

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

What is a set in Python?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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

What is the difference between string and variable?

A

A variable is used to store a string . A string is not used to store variable.

47
Q

describe booleans

A

Boolean- TRUE and FALSE are Boolean data types. Non Boolean objects can also be evaluated as Boolean . eg 1==0, returns FALSE , 2==2 returns TRUE

48
Q

How do you add and remove elements from a set?

A

add(): Adds an element to the set.
remove(): Removes an element from the set. If the element doesn’t exist, it raises a KeyError.
discard(): Removes an element if it exists in the set, but doesn’t raise an error if it doesn’t.
my_set = {1, 2, 3}
my_set.add(4) # Adds 4
my_set.remove(2) # Removes 2
my_set.discard(3) # Removes 3, no error if element doesn’t exist
print(my_set)

49
Q

What is an expression made up of? What do all expressions do?

A

A combination of operands and operators is called an expression, they serve as representations of value. The result of an expression can be of any data type, like an integer, float, string, boolean, list, etc

50
Q

This assignment statements, like spam = 10. What is the difference between an expression and a statement?

A

Expression is a representation of a value or evaluates to a value. Statement is used for creating variables or for displaying values. Statements represent a motion or command e.g print statements,if statements etc.

51
Q

After running the following code, what does the variable bacon contain?
bacon = 22
bacon + 1

A

Variable bacon will still contain 22. Bacon +1 could give 23 only if it was assigned to the bacon variable . i.e bacon=bacon +1

52
Q

‘spam’ * 3 output?

A

‘spamspamspam’

53
Q

Why is eggs a valid variable name while 100 is invalid?

A

Variable names must start with a letter be it capital or small but cannot start with a number. However numbers can be used only if the starting name of the variable is a alphabet.

54
Q

What three functions can be used to get the integer, floating-point number, or string version of a value?

A

Typecasting , in codes executed as int(a),float(a),str(a) respectlively.

55
Q

Why does this expression cause an error? How can you fix it?
‘I have eaten ‘ + 99 + ‘ burritos.’

A

Concatenating different types of datatypes are not allowed in python. It can be fixed by turning 99 into string by changing into ‘99’ or str(99).

56
Q

What are the three different types of Boolean operators?

A

“and” “or” “not” . They return results for multiple conditions where more than True and False results can be involved . “and” operator only returns True if both operands are True.”or” returns True if any one of the operands is True. “not” returns the invert of the operand .

57
Q

How do you tell the difference between the equal to and assignment operators? Describe a condition and when you would use one.

A

The ‘=’ is the so-called assignment operator and is used to assign the result of the expression on the right side of the operator to the variable on the left side. Eg a= 35, b= “hello” etc . The ‘==’ is the so-called equality comparison operator and is used to check whether the two expressions on both sides are equal or not. Eg (3==5) , (a==5)

58
Q

How can you tell the difference between break and continue?

A

Break statement stops the entire process of the loop. Continue statement only stops the current iteration of the loop. Break also terminates the remaining iterations. Continue doesn’t terminate the next iterations; it resumes with the successive iterations.

59
Q

In a for loop, what is the difference between range(10), range(0, 10), and range(0, 10, 1)?

A

All three produce same (0,1,2…9)
But range 10 generates no from 0 to 9 not including 10
Range(0,10) explicitly tells to start from 0 and end with 10.
Range(0,10,1) specifies start as 0 stop as 10 and step size as 1. Generates numbers where they are incremented by 1 each time. If it was two then result would be 0,2,4,…10.

60
Q

What exactly is []?

A

[] represents an empty list in Python.

61
Q

In a list of values stored in a variable called spam, how would you assign the value ‘hello’ as the third value? (Assume [2, 4, 6, 8, 10] are in spam.)

A

spam[2] = ‘hello’

62
Q

calculate (‘3’ * 2) / 11)

A

‘3’ * 2 returns ‘33’, int(‘33’) converts it to 33, 33 / 11 is 3.

63
Q

How does bacon.append(99) change the look of the list value in bacon?

A

bacon.append(99) adds 99 to the end of the list

64
Q

What are the list concatenation and list replication operators?

A

The list concatenation operator is +, and the list replication operator is *

65
Q

What is difference between the list methods append() and insert()?

A

append() adds an item to the end of the list, while insert() allows us to add an item at a specific index.

66
Q

What’s the difference between tuples and lists?

A

Lists are mutable, tuples are immutable.

67
Q

Variables that “contain” list values are not necessarily lists themselves. Instead, what do they contain?

A

Variables that “contain” list values actually contain references to the list objects, not the list itself.

68
Q

How do you distinguish between copy.copy() and copy.deepcopy()?

A

copy.copy() creates a shallow copy, copying the list structure but not nested objects.
copy.deepcopy() creates a deep copy, copying everything, including all nested objects.

69
Q
A