#2 – Data Types Flashcards
(17 cards)
When should you use a tuple in Python?
Use a tuple when your data is fixed and should not change.coordinates = (10, 20)
When should you use a list in Python?
Use a list when you need an ordered, mutable collection.fruits = ['apple', 'banana']
When should you use a set in Python?
Use a set when you need a collection of unique, unordered items.unique_items = set([1, 2, 2, 3])
When should you use a dictionary in Python?
Use a dictionary when you want to associate keys with values.person = {'name': 'Alice', 'age': 30}
Example:
What is a namedtuple and when should you use it?
A namedtuple is like a tuple, but with named fields. It makes code more readable.
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p.x)
What is a defaultdict and when should you use it?
A defaultdict is like a normal dictionary, but it automatically creates default values for missing keys.
from collections import defaultdict d = defaultdict(int) d['a'] += 1 print(d['a']) # 1
How do you get the length of a list?
Use the len() function.len(my_list)
How do you get the last element of a list?
Use negative indexing.
my_list = [10, 20, 30] print(my_list[-1]) # 30
How do you get the length of a list?
Use the len() function.
len(my_list)
How do you add an element to the end of a list?
Use .append().
my_list.append(100)
How do you add multiple elements to a list?
Use .extend().
my_list.extend([4, 5])
How do you insert an element at a specific index?
Use .insert(index, value).
my_list.insert(1, 'x')
How do you remove an element by value?
Use .remove(value).
my_list.remove('x')
How do you remove an element by index?
Use del or .pop().
del my_list[2]or
my_list.pop(2)
How do you get a sublist (slice)?
Use slicing syntax.
my_list[1:3] # from index 1 to 2
How do you reverse a list (non-destructive)?
Use slicing with step -1.
reversed_list = my_list[::-1]
How do you check if an element is in a list?
Use the ‘in’ keyword. 'if 10 in my_list:'