A list is an ordered, mutable collection that can store multiple items. Lists are one of the most useful and flexible data types in Python.
Why Lists?
Store multiple related items together
Grow and shrink dynamically
Support powerful operations like slicing, filtering, and transformations
Creating Lists
# Empty list
empty_list = []
print (empty_list)
# With initial items
fruits = ["apple" , "banana" , "cherry" ]
print (fruits)
# Mixed types
mixed = ["Alice" , 30 , 5.7 , True ]
print (mixed)
# Nested list (list of lists)
matrix = [[1 , 2 ], [3 , 4 ], [5 , 6 ]]
print (matrix)
[]
['apple', 'banana', 'cherry']
['Alice', 30, 5.7, True]
[[1, 2], [3, 4], [5, 6]]
Exercise: Create a list of three cities and print it.
cities = ["Tokyo" , "Paris" , "New York" ]
print (cities)
['Tokyo', 'Paris', 'New York']
Types of Lists
Homogeneous Lists (same type)
numbers = [1 , 2 , 3 , 4 ]
names = ["Alice" , "Bob" , "Cara" ]
Heterogeneous Lists (mixed types)
mixed = ["Alice" , 30 , 5.7 , True ]
Nested Lists (lists inside lists)
matrix = [[1 , 2 ], [3 , 4 ], [5 , 6 ]]
Exercise: Create a nested list representing a 2×3 grid, then access the item in row 2, column 3.
grid = [
[1 , 2 , 3 ], # row 1
[4 , 5 , 6 ] # row 2
]
print (grid[1 ][2 ]) # row 2, col 3 -> 6
Indexing & Slicing
fruits = ["apple" , "banana" , "cherry" , "date" , "elderberry" ]
print (fruits[0 ]) # first item
print (fruits[- 1 ]) # last item
# Slicing: list[start:stop]
print (fruits[1 :4 ]) # items at indexes 1, 2, 3
print (fruits[:3 ]) # first three items
print (fruits[2 :]) # from index 2 to the end
print (fruits[- 2 :]) # last two items
print (fruits[::2 ]) # step of 2
apple
elderberry
['banana', 'cherry', 'date']
['apple', 'banana', 'cherry']
['cherry', 'date', 'elderberry']
['date', 'elderberry']
['apple', 'cherry', 'elderberry']
Exercise: Given nums = [10, 20, 30, 40, 50, 60]
, slice to get:
The first three numbers
The last two numbers
Every other number (step=2)
nums = [10 , 20 , 30 , 40 , 50 , 60 ]
first_three = nums[:3 ]
last_two = nums[- 2 :]
every_other = nums[::2 ]
print (first_three, last_two, every_other)
[10, 20, 30] [50, 60] [10, 30, 50]
Adding Elements
fruits = ["apple" , "banana" ]
fruits.append("cherry" ) # add to end
fruits.insert(1 , "mango" ) # insert at index 1
fruits.extend(["date" , "fig" ]) # extend with another list
print (fruits)
['apple', 'mango', 'banana', 'cherry', 'date', 'fig']
Exercise: Start with colors = ["red", "green"]
and:
Insert "blue"
at index 1
Append "yellow"
Extend with ["black", "white"]
Print the result.
colors = ["red" , "green" ]
colors.insert(1 , "blue" )
colors.append("yellow" )
colors.extend(["black" , "white" ])
print (colors)
['red', 'blue', 'green', 'yellow', 'black', 'white']
Removing Elements
fruits = ["apple" , "banana" , "cherry" , "banana" ]
fruits.remove("banana" ) # removes first occurrence
popped = fruits.pop(1 ) # removes by index, returns item
del fruits[0 ] # delete by index (no return)
print ("After removals:" , fruits)
print ("Popped item:" , popped)
After removals: ['banana']
Popped item: cherry
Exercise 5: Given nums = [5, 10, 15, 20, 25]
, remove the middle value using pop()
and print the updated list and the removed value.
nums = [5 , 10 , 15 , 20 , 25 ]
mid_index = len (nums)// 2
removed = nums.pop(mid_index)
print (nums, removed)
Updating Elements
prices = [9.99 , 14.99 , 4.99 ]
prices[0 ] = 8.99
prices[1 :3 ] = [12.99 , 3.99 ] # slice assignment
print (prices)
Exercise 6: Replace the last two elements of letters = ['a', 'b', 'c', 'd']
with ['x', 'y']
using slice assignment.
letters = ['a' , 'b' , 'c' , 'd' ]
letters[- 2 :] = ['x' , 'y' ]
print (letters)
Looping Through Lists
fruits = ["apple" , "banana" , "cherry" ]
for fruit in fruits:
print (fruit)
# With index using enumerate
for idx, fruit in enumerate (fruits):
print (idx, fruit)
apple
banana
cherry
0 apple
1 banana
2 cherry
Exercise: Loop through names = ['Ann', 'Ben', 'Cara']
and print each name with its index (starting from 1).
names = ['Ann' , 'Ben' , 'Cara' ]
for i, name in enumerate (names, start= 1 ):
print (i, name)
Useful List Methods
nums = [4 , 1 , 3 , 2 ]
nums.sort() # sort ascending (in place)
print ("sorted:" , nums)
nums.reverse() # reverse order (in place)
print ("reversed:" , nums)
print ("count of 2:" , nums.count(2 ))
print ("index of 3:" , nums.index(3 ))
sorted: [1, 2, 3, 4]
reversed: [4, 3, 2, 1]
count of 2: 1
index of 3: 1
Exercise: Given nums = [10, 5, 8, 5, 3]
, sort the list ascending, count how many 5
s there are, and find the index of 8
.
nums = [10 , 5 , 8 , 5 , 3 ]
nums.sort()
count_5 = nums.count(5 )
idx_8 = nums.index(8 )
print (nums, count_5, idx_8)
List Comprehensions
# Square numbers 0..5
squares = [x** 2 for x in range (6 )]
print (squares)
# Filter even numbers
evens = [x for x in range (10 ) if x % 2 == 0 ]
print (evens)
# Transform strings
names = ["alice" , "bob" , "cara" ]
caps = [n.title() for n in names]
print (caps)
[0, 1, 4, 9, 16, 25]
[0, 2, 4, 6, 8]
['Alice', 'Bob', 'Cara']
Exercise: Using nums = [1, 2, 3, 4, 5, 6]
, build a new list of squares only for the odd numbers .
nums = [1 , 2 , 3 , 4 , 5 , 6 ]
odd_squares = [x** 2 for x in nums if x % 2 == 1 ]
print (odd_squares)
Summary
Lists are ordered and mutable
Support indexing, slicing, adding/removing, updating, and iterating
Powerful methods and list comprehensions make data processing concise
Practice: Consolidated Exercises
Create a list pets
with three animal names. Append one more.
From grades = [60, 70, 80, 90, 100]
, slice the last three grades.
Replace the first two items in tools = ['hammer', 'screwdriver', 'wrench']
with ['saw', 'drill']
.
Use a loop to print each item in colors = ['red', 'green', 'blue']
with its index.
Use a comprehension to create [x*10 for x in [1,2,3,4]]
.
# 1) pets list
pets = ["cat" , "dog" , "hamster" ]
pets.append("parrot" )
print (pets)
# 2) slice last three grades
grades = [60 , 70 , 80 , 90 , 100 ]
print (grades[- 3 :])
# 3) replace first two items
tools = ['hammer' , 'screwdriver' , 'wrench' ]
tools[:2 ] = ['saw' , 'drill' ]
print (tools)
# 4) loop with index
colors = ['red' , 'green' , 'blue' ]
for i, c in enumerate (colors):
print (i, c)
# 5) comprehension * 10
print ([x* 10 for x in [1 ,2 ,3 ,4 ]])
['cat', 'dog', 'hamster', 'parrot']
[80, 90, 100]
['saw', 'drill', 'wrench']
0 red
1 green
2 blue
[10, 20, 30, 40]
Working with Nested Lists (Matrices)
This notebook demonstrates how to access elements in a nested list (list of lists), like a matrix or table.
Example: A 3x2 Matrix
matrix = [
[1 , 2 ], # row 0
[3 , 4 ], # row 1
[5 , 6 ] # row 2
]
print (matrix)
Accessing Specific Elements
print (matrix[0 ][0 ]) # 1 (row 0, column 0)
print (matrix[0 ][1 ]) # 2 (row 0, column 1)
print (matrix[2 ][0 ]) # 5 (row 2, column 0)
Looping Through a Matrix
for row in matrix:
for item in row:
print (item, end= ' ' )
print () # new line after each row