Lists are one of the most versatile and commonly used data structures in Python. They allow you to store multiple items in a single variable.
[].Example:
#A list of fruits
fruits = ["apple", "banana", "cherry"]
#A mixed-type list
mixed_list = [42, "hello", 3.14]
Creating a List:
fruits = ["apple", "banana", "cherry"]
Accessing Items:
0 for the first item).-1 for the last item).print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
Modifying Items:
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
Appending Items:
fruits.append("grape")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'grape']
Inserting Items:
fruits.insert(1, "kiwi")
print(fruits) # Output: ['apple', 'kiwi', 'orange', 'cherry', 'grape']
Removing Items:
Remove by value:
fruits.remove("orange")
print(fruits) # Output: ['apple', 'kiwi', 'cherry', 'grape']
Remove by index:
fruits.pop(0) # Removes 'apple'
print(fruits) # Output: ['kiwi', 'cherry', 'grape']
Sorting Items:
fruits.sort()
print(fruits) # Output: ['cherry', 'grape', 'kiwi']
Reversing Items:
fruits.reverse()
print(fruits) # Output: ['kiwi', 'grape', 'cherry']
list[start:end] (start inclusive, end exclusive).sublist = fruits[1:3]
print(sublist) # Output: ['grape', 'cherry']
for loop to iterate through items.for fruit in fruits:
print(fruit)
Output:
kiwi
grape
cherry
Tuples are similar to lists but immutable, meaning their contents cannot be changed after creation.
().Example:
coordinates = (10, 20)
Creating a Tuple:
numbers = (1, 2, 3)
Accessing Items:
print(coordinates[0]) # Output: 10
coordinates[0] = 15 # TypeError: 'tuple' object does not support item assignment
Returning Multiple Values:
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
print(x, y) # Output: 10 20
Using Tuples as Keys:
Dictionaries are collections of key-value pairs, where each key is unique.
{}.Example:
person = {"name": "Alice", "age": 25}
Creating a Dictionary:
person = {"name": "Alice", "age": 25}
Accessing Values:
print(person["name"]) # Output: Alice
Adding or Updating Items:
person["city"] = "New York"
print(person) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
Deleting Items:
del.del person["age"]
print(person) # Output: {'name': 'Alice', 'city': 'New York'}
keys():
print(person.keys()) # Output: dict_keys(['name', 'city'])
values():
print(person.values()) # Output: dict_values(['Alice', 'New York'])
items():
print(person.items()) # Output: dict_items([('name', 'Alice'), ('city', 'New York')])
Strings are sequences of characters enclosed in quotes.
' or double " quotes.Example:
text = "Hello, world!"
Accessing Characters:
print(text[0]) # Output: H
print(text[-1]) # Output: !
Slicing:
substring = text[0:5]
print(substring) # Output: Hello
upper():
Convert to uppercase.
print("hello".upper()) # Output: HELLO
lower():
Convert to lowercase.
print("HELLO".lower()) # Output: hello
strip():
Remove leading and trailing whitespace.
print(" hello ".strip()) # Output: hello
split():
Split the string into a list.
print("a,b,c".split(",")) # Output: ['a', 'b', 'c']
join():
Join a list of strings into one string.
print(",".join(["a", "b", "c"])) # Output: a,b,c
Using f-strings:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 25 years old.
in and not in Operators in Lists and DictionariesThe in operator is used to check if a value exists in a collection (e.g., a list or dictionary). not in does the opposite.
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" not in fruits) # True
"apple" is an element in the list.person = {"name": "Alice", "age": 25}
print("name" in person) # True → checks if "name" is a key
print("Alice" in person) # False → values are not searched
in only checks the keys, not values.You might see a question like:
info = {"x": 100}
print(100 in info)
False, because 100 is a value, not a key.get()When accessing values in a dictionary, there are two main methods:
person = {"name": "Alice"}
print(person["city"]) # Raises KeyError if "city" is not a key
.get()print(person.get("city")) # Returns None instead of crashing
.get() is safer and avoids a KeyError.You may see a question testing which line is safe to run without error. Always consider using .get() if the key might be missing.
A string in Python is an iterable object, meaning you can loop through its characters just like a list.
for ch in "hi":
print(ch)
Output:
h
i
This is important in the context of for loops and demonstrates that strings behave like sequences.
Slicing syntax is the same across different sequence types in Python, but the resulting data type matches the original.
text = "abcde"
print(text[1:4]) # Output: 'bcd' (still a string)
lst = ["a", "b", "c", "d", "e"]
print(lst[1:4]) # Output: ['b', 'c', 'd'] (still a list)
The slice returns the same type as the original sequence.
Be cautious not to confuse string slices with list slices, especially in multiple-choice questions.
{} Is Not an Empty Set in PythonThis is a very common misconception.
a = {} # This is an empty dictionary
b = set() # This is an empty set
{} always creates a dictionary, even if it's empty.
To create an empty set, you must use set().
Using {} when you intend to create a set can cause silent logic errors or confusion in type-checking.
print(type({})) # <class 'dict'>
print(type(set())) # <class 'set'>
| Feature | Code Example | Output | Key Takeaway |
|---|---|---|---|
in with list |
"apple" in ["apple", "banana"] |
True |
Checks list elements |
in with dict |
"name" in {"name": "Alice"} |
True |
Checks keys only |
.get() vs [] |
dict.get("missing") |
None |
Safer than dict["missing"] |
| String is iterable | for ch in "hi" |
hi | String acts like a sequence |
| String slicing | "abcde"[1:4] |
'bcd' |
Returns a string |
| List slicing | ["a","b","c","d"][1:3] |
['b','c'] |
Returns a list |
| Empty dictionary | {} |
<class 'dict'> |
Not a set! |
| Empty set | set() |
<class 'set'> |
Correct syntax |
What is the main difference between a list and a tuple in Python?
Lists are mutable, while tuples are immutable.
A list allows modification after creation (e.g., adding or changing elements), whereas a tuple cannot be changed once defined. This immutability makes tuples faster and safer for fixed data. A common mistake is attempting to modify tuple elements, which raises a TypeError. Choosing between them depends on whether data needs to change.
Demand Score: 85
Exam Relevance Score: 92
Why does modifying a tuple raise an error?
Because tuples are immutable and do not support item assignment.
Once a tuple is created, its elements cannot be altered. Attempting to change a value results in a TypeError. This design ensures data integrity. A common misunderstanding is treating tuples like lists. To modify data, you must create a new tuple instead.
Demand Score: 83
Exam Relevance Score: 90
Why do I get a KeyError when accessing a dictionary?
A KeyError occurs when the specified key does not exist in the dictionary.
Dictionaries require exact key matches. Accessing a missing key raises an error. This often happens due to typos or incorrect assumptions about data structure contents. Using methods like get() can avoid crashes. A common mistake is assuming a key exists without validation.
Demand Score: 90
Exam Relevance Score: 93
Why can’t I modify a string directly in Python?
Strings are immutable, so their characters cannot be changed after creation.
Any operation that appears to modify a string actually creates a new one. Attempting direct assignment like s[0] = 'a' results in an error. A common mistake is treating strings like lists. Proper modification requires creating a new string using slicing or methods.
Demand Score: 88
Exam Relevance Score: 91
How does list indexing and slicing work in Python?
Indexing accesses a single element, while slicing retrieves a subset of elements.
Lists use zero-based indexing. For example, list[0] returns the first element. Slicing uses syntax like list[1:4], returning elements from index 1 to 3. A common mistake is misunderstanding that the end index is exclusive. Negative indices can access elements from the end.
Demand Score: 82
Exam Relevance Score: 89
What is the difference between accessing and modifying elements in a dictionary?
Accessing retrieves a value, while modifying changes or adds a key-value pair.
Access uses dict[key], while modification assigns dict[key] = value. If the key exists, the value updates; if not, a new pair is created. A common mistake is expecting an error when adding a new key, but Python allows it.
Demand Score: 80
Exam Relevance Score: 88