WEEK 2, deel 2 Flashcards
What is a list in Python?
A list is a data structure that stores multiple values in an ordered sequence.
What happens if you try to access an index that doesn’t exist?
Python raises an IndexError.
How do negative indexes work in lists?
-1 refers to the last item.
-2 refers to the second-last item.
spam = [[‘cat’, ‘bat’], [10, 20, 30, 40, 50]]
print(spam[0])
print(spam[1][4])
First inner list: cat bat
# 5th item in second list: 50
What kinds of values can be in a list?
Lists can contain any type of values
What is the difference between indexing and slicing?
Indexing (spam[0]) gets one item.
Slicing (spam[1:3]) gets a range of items.
Syntax of Slicing
list[start:stop]
start: The index where slicing begins (included).
stop: The index where slicing ends (not included).
How do you change a value in a list?
Assign a new value using indexing.
spam = [‘cat’, ‘bat’, ‘rat’, ‘elephant’]
spam[1] = ‘dog’ # Change ‘bat’ to ‘dog’
print(spam)
How do you add or remove items in a list?
Use .append(value) to add an item.
Use .remove(value) to delete an item.
How do you check if a value is in a list?
Use the in keyword.
How do you sort a list in Python?
Use .sort() for ascending order, .sort(reverse=True) for descending order.
What is the safest way to copy a list?
Use .copy() to avoid modifying the original list.
spam = [‘cat’, ‘bat’, ‘rat’, ‘elephant’]
print(spam[:2])
print(spam[1:])
First 2 items: cat, bat
From index 1 to the end: bat, rat, elephant
what happens if you concatenation and replication lists
concatenation: +, joints two lists
replication: *, repeats a list
what’s the relationship between range(len(supplies)) and enumerate()
enumerate() automatically gives us both: the index and the value.
hat are augmented assignment operators, and how do they work?
They are shorthand for modifying a variable.
spam += 1 spam = spam + 1
spam -= 1 spam = spam - 1
spam *= 1 spam = spam * 1
spam /= 1 spam = spam / 1
spam %= 1 spam = spam % 1
What is the difference between mutable and immutable data types?
Mutable → Can be changed (e.g., lists).
Immutable → Cannot be changed (e.g., strings, tuples).
name = “Zophie a cat”
new_name = name[0:7] + “the” + name[8:12]
print(new_name)
Zophie the cat
How is a tuple different from a list?
Tuples use () instead of [].
Tuples are immutable (cannot change values).
spam = [0, 1, 2, 3, 4, 5]
cheese = spam # Both refer to the same list
cheese[1] = “Hello!”
print(spam) # spam is also changed
[0, ‘Hello!’, 2, 3, 4, 5]