Python List Fundamentals and Operations
A list in Python holds an ordered collection of items. Its defined with square brackets, and the items are separated by commas.
numbers = [10, 20, 30, 40]
names = ["alice", "bob", "carol"]
Accessing Items
By Index
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
Using Methods
index(item, start, end)
Returns the first index of the item. Raises ValueError if the item is absent.
colors = ["red", "green", "blue", "green"]
print(colors.index("green")) # 1
# print(colors.index("yellow")) # ValueError
count(item)
Returns how many times an item appears. Returns 0 if the item does not exist.
colors = ["red", "green", "blue", "green"]
print(colors.count("green")) # 2
print(colors.count("yellow")) # 0
len(list)
Returns the total number of items in the list.
tools = ["hammer", "screwdriver", "wrench"]
print(len(tools)) # 3
Membership Tests
in
Returns True if the item is present.
devices = ["phone", "tablet", "laptop"]
print("tablet" in devices) # True
print("watch" in devices) # False
not in
Returns True if the item is absent.
devices = ["phone", "tablet", "laptop"]
print("watch" not in devices) # True
Adding Items
append(item)
Adds an item to the end of the list.
items = [1, 2, 3]
items.append(4)
print(items) # [1, 2, 3, 4]
extend(iterable)
Extends the list by appending each element from the iterable. When extending with a string, every character becomes a separate element.
chars = ["x", "y"]
chars.extend("ab")
print(chars) # ['x', 'y', 'a', 'b']
more = ["p", "q"]
more.extend(["r", "s"])
print(more) # ['p', 'q', 'r', 's']
insert(index, item)
Inserts an item at a specific position. Existing items shift to the right.
grades = ["A", "B", "D"]
grades.insert(2, "C")
print(grades) # ['A', 'B', 'C', 'D']
Removing Items
del list[index]
Deletes an item at a given index, or the whole list if no index is provided.
values = [100, 200, 300, 400]
del values[1]
print(values) # [100, 300, 400]
pop(index)
Removes and returns the item at the specified index. The last item is removed if no index is given.
cities = ["Paris", "London", "Tokyo"]
removed = cities.pop(1)
print(removed) # London
print(cities) # ['Paris', 'Tokyo']
remove(item)
Removes the first occurrence of the item. A ValueError is raised if the item is not found.
letters = ["a", "b", "c", "b"]
letters.remove("b")
print(letters) # ['a', 'c', 'b']
clear()
Empties the list, leaving [].
data = [1, 2, 3]
data.clear()
print(data) # []
Modifying Items
Direct assignment
shapes = ["circle", "square", "triangle"]
shapes[1] = "rectangle"
print(shapes) # ['circle', 'rectangle', 'triangle']
reverse()
Reverses the order of the items in place.
nums = [1, 3, 5, 7]
nums.reverse()
print(nums) # [7, 5, 3, 1]
sort(key=None, reverse=False)
Sorts the list in place. Set reverse=True for descending order.
scores = [88, 92, 75, 83]
scores.sort()
print(scores) # [75, 83, 88, 92]
scores.sort(reverse=True)
print(scores) # [92, 88, 83, 75]
Copying a List
copy()
Creates a shallow copy of the list.
original = [10, 20, 30]
duplicate = original.copy()
print(duplicate) # [10, 20, 30]
# Changing the copy does not affect the original
duplicate[0] = 99
print(original) # [10, 20, 30]
Iterating Over a List
while loop
tasks = ["write", "test", "deploy"]
index = 0
while index < len(tasks):
print(tasks[index])
index += 1
for loop
tasks = ["write", "test", "deploy"]
for task in tasks:
print(task)
Nested Lists
A list can contain other lists, forming a 2D (or higher) structure.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0]) # [1, 2, 3]
print(matrix[1][2]) # 6
mixed = ["text", 42, [True, None]]
print(mixed[2][0]) # True