Lists and list methods
What Are Lists in Python?
A list is a built-in data structure in Python that is used to store multiple items in a single variable. Lists are ordered, mutable, and can contain elements of mixed data types (strings, numbers, booleans, other lists, etc.).
List Syntax
my_list = [1, 2, 3, “hello”, True]
- Items are separated by commas.
- Enclosed in square brackets [].
- Indexed starting from 0.
Accessing List Items
fruits = [“apple”, “banana”, “cherry”]
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry (negative index = from end)
Common List Methods
Python provides many built-in methods to manipulate lists:
append(item)
Adds a new item to the end of the list.
fruits.append(“orange”)
insert(index, item)
Inserts an item at a specific position.
fruits.insert(1, “kiwi”) # Inserts “kiwi” at index 1
extend(iterable)
Extends the list by appending elements from another iterable (like another list).
fruits.extend([“mango”, “grape”])
remove(item)
Removes the first occurrence of the specified value.
fruits.remove(“banana”)
pop([index])
Removes and returns the item at the given index (or last item if no index is given).
last_fruit = fruits.pop() # Removes last item
clear()
Removes all items from the list.
fruits.clear()
index(item)
Returns the index of the first occurrence of the specified item.
idx = fruits.index(“apple”)
count(item)
Returns the number of times a value appears in the list.
nums = [1, 2, 2, 3, 2]
print(nums.count(2)) # Output: 3
sort()
Sorts the list in-place (modifies the original list). For ascending order by default.
numbers = [4, 2, 9, 1]
numbers.sort()
Use numbers.sort(reverse=True) for descending.
sorted(list)
Returns a new sorted list without modifying the original.
sorted_numbers = sorted(numbers)
reverse()
Reverses the elements of the list in-place.
numbers.reverse()
copy()
Creates a shallow copy of the list.
new_list = fruits.copy()
Looping Through Lists:
for fruit in fruits:
print(fruit)
List Slicing
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # Output: [1, 2, 3]
print(nums[:3]) # Output: [0, 1, 2]
print(nums[::2]) # Output: [0, 2, 4]
Lists Are Mutable
You can modify individual items:
nums[0] = 100
And delete with del:
del nums[2]
Summary
- Lists are ordered, mutable, and can hold mixed data types.
- Access items using indexes.
- Modify lists with built-in methods like append(), remove(), sort(), and more.
- Use slicing, loops, and comprehensions for powerful list operations.
Tuples and tuple unpacking
What Are Tuples?
A tuple is a built-in data type in Python used to store multiple items in a single, ordered, immutable collection.
- Like a list, but cannot be changed (immutable) after creation.
- Often used for fixed data (e.g., coordinates, RGB colors, function returns).
Tuple Syntax
my_tuple = (1, 2, 3)
- Defined with parentheses () — although parentheses are optional.
- Elements separated by commas.
- Can hold mixed data types.
One-item tuple (very important!)
To define a tuple with one item, you must include a comma:
single = (5,) # This is a tuple
not_a_tuple = (5) # This is just an int
Accessing Tuple Elements
Tuples are indexed, just like lists:
colors = (“red”, “green”, “blue”)
print(colors[0]) # red
print(colors[-1]) # blue
Looping Through Tuples
for color in colors:
print(color)
Tuples Are Immutable
You cannot change, add, or remove items from a tuple:
colors[0] = “yellow” # TypeError
Tuple Methods
- Tuples have fewer methods than lists due to immutability:
- count(value) – returns the number of times a value appears.
- index(value) – returns the index of the first matching value.
nums = (1, 2, 2, 3)
print(nums.count(2)) # 2
print(nums.index(3)) # 3
Tuple Unpacking
Tuple unpacking lets you assign values from a tuple to multiple variables in one line.
Basic Unpacking
point = (10, 20)
x, y = point
print(x) # 10 print(y) # 20
The number of variables must match the number of tuple items.
Swapping Variables (Pythonic Way)
a = 5
b = 10
a, b = b, a
print(a, b) # Output: 10 5
No need for a temporary variable!
Unpacking with * (Extended Unpacking)
a, *b = (1, 2, 3, 4)
print(a) # 1
print(b) # [2, 3, 4]
a, *b, c = (1, 2, 3, 4, 5)
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5
Tuple Unpacking in Functions
You can return multiple values from a function using a tuple:
def get_user():
return “Alice”, 30 # returns a tuple
name, age = get_user()
print(name) # Alice
print(age) # 30
Summary:
- Tuples are ordered, immutable sequences.
- Useful for fixed data or function returns.
- Use tuple unpacking to assign values in a clean way.
- Tuples support indexing, looping, and limited methods (count(), index()).
Dictionaries and dictionary methods
What Is a Dictionary?
A dictionary is a collection of key-value pairs, where each key is unique, and each key maps to a specific value. Think of it like a real dictionary: each word (key) has a definition (value).
Dictionary Syntax
my_dict = {
“name”: “Alice”,
“age”: 30,
“is_active”: True
}
- Keys and values are separated by colons.
- Pairs are separated by commas.
- Enclosed in curly braces {}.
Accessing Values
print(my_dict[“name”]) # Output: Alice
Use the key to access the value.
Using get() Method
print(my_dict.get(“name”)) # Alice
print(my_dict.get(“email”, “N/A”)) # N/A if key not found
Safer than bracket access because it avoids KeyError.
Adding & Updating Items
my_dict[“email”] = “alice@example.com” # Add new
my_dict[“age”] = 31 # Update existing
Removing Items
my_dict.pop(“age”) # Removes and returns the value for ‘age’
del my_dict[“is_active”] # Removes key ‘is_active’
Clearing the Dictionary
my_dict.clear() # Removes all items
Dictionary Methods
Here are some of the most commonly used dictionary methods:
Method | Description |
---|---|
get(key, default) |
Returns value for key, or default if key not found |
keys() |
Returns a view object of all keys |
values() |
Returns a view object of all values |
items() |
Returns a view object of (key, value) pairs |
update(dict2) |
Merges dictionary with another dictionary’s key-value pairs |
pop(key) |
Removes and returns the item with the specified key |
popitem() |
Removes and returns the last inserted (key, value) pair |
clear() |
Removes all items from the dictionary |
Example: Looping Through a Dictionary
for key in my_dict:
print(key, my_dict[key])
Or with .items()
for key, value in my_dict.items():
print(f”{key}: {value}”)
Check If a Key Exists
if “name” in my_dict:
print(“Found name”)
Dictionary Comprehensions
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Nesting Dictionaries
users = {
“alice”: {“age”: 25, “email”: “a@example.com”},
“bob”: {“age”: 30, “email”: “b@example.com”}
}
print(users[“bob”][“email”]) # b@example.com
Summary:
- Dictionaries store key-value pairs and are unordered (but maintain insertion order in Python 3.7+).
- Keys must be immutable and unique (e.g., strings, numbers, tuples).
- Use methods like .get(), .items(), .update(), and .pop() to work with them efficiently.
- Great for representing structured data, such as JSON, configurations, and more.
Sets and set operations
What Is a Set in Python?
A set is an unordered, mutable, and unindexed collection of unique elements. Sets are great when you need to eliminate duplicates or perform set-based logic.
Set Syntax
my_set = {1, 2, 3, 4}
- Use curly braces {} or the set() constructor.
- Duplicate values are automatically removed.
Creating an empty set must use set() — {} creates an empty dictionary, not a set.
empty_set = set()
Example: Duplicates Removed Automatically
nums = {1, 2, 2, 3, 3}
print(nums) # Output: {1, 2, 3}
Common Set Methods
Method | Description |
---|---|
add(item) |
Adds a single item to the set |
update(iterable) |
Adds multiple items from an iterable |
remove(item) |
Removes the specified item (raises KeyError if item doesn’t exist) |
discard(item) |
Removes the specified item (does nothing if item doesn’t exist) |
pop() |
Removes and returns an arbitrary item from the set (raises KeyError if empty) |
clear() |
Removes all items from the set |
copy() |
Returns a new set with a shallow copy of the elements |
Example Methods:
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
s.update([5, 6]) # {1, 2, 3, 4, 5, 6}
s.remove(3) # {1, 2, 4, 5, 6}
s.discard(10) # No error if 10 isn’t there
Looping Through a Set
for item in s:
print(item)
Order is not guaranteed in sets.
Set Operations (like in Math)
union() or |
Combine all unique elements from both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a.union(b)) # Same
intersection() or &
Get only the elements common to both sets.
print(a & b) # {3}
print(a.intersection(b)) # Same
difference() or –
Get elements that are in the first set but not in the second.
print(a – b) # {1, 2}
print(a.difference(b)) # Same
symmetric_difference() or ^
Get elements in either set, but not both.
print(a ^ b) # {1, 2, 4, 5}
print(a.symmetric_difference(b)) # Same
Set Comparisons
Operation | Meaning | Example |
---|---|---|
== |
Sets contain exactly the same elements | {1, 2} == {2, 1} → True |
issubset() |
All elements of set A exist in set B | {1, 2}.issubset({1, 2, 3}) → True |
issuperset() |
All elements of set B exist in set A | {1, 2, 3}.issuperset({1, 2}) → True |
isdisjoint() |
Sets share no common elements | {1, 2}.isdisjoint({3, 4}) → True |
Example:
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b)) # True
print(b.issuperset(a)) # True
print(a.isdisjoint({4})) # True
Summary:
- Sets store unique, unordered values.
- Use sets to remove duplicates and perform mathematical operations.
- Built-in methods like union(), intersection(), and difference() make sets powerful for logic and data comparisons.
Want to learn about frozensets (immutable sets), set comprehensions, or use cases like duplicates removal in lists? Just let me know!