A list is an ordered, changeable collection that can hold items of any type. Lists are the most used data structure in Python, and you will use them constantly in data science before moving to NumPy arrays and Pandas.
What You Will Learn
- Creating, indexing and slicing lists
- Adding, removing and sorting items
- List comprehensions
- Copying lists safely
Prerequisites
Python Strings (indexing and slicing work the same way).
Creating a List
marks = [85, 92, 78]
mixed = ['Asha', 21, 5.4, True]
empty = []
print(len(marks), marks[0], marks[-1], marks[0:2])
3 85 78 [85, 92]
Changing Items
marks = [85, 92, 78]
marks[1] = 95
print(marks)
Explanation: Unlike strings, lists are mutable: you can change items in place.
[85, 95, 78]
Adding Items
nums = [1, 2]
nums.append(3) # add at end
nums.insert(0, 0) # add at index 0
nums.extend([4, 5]) # add many
print(nums)
[0, 1, 2, 3, 4, 5]
Removing Items
nums = [10, 20, 30, 20, 40]
nums.remove(20) # first matching value
last = nums.pop() # remove and return last
del nums[0] # by index
print(nums, last)
[30, 20] 40
Useful Methods
nums = [5, 2, 9, 1]
print(sorted(nums), nums)
nums.sort(reverse=True)
print(nums, nums.index(9), nums.count(2))
| Method | What it does |
|---|---|
sort() |
Sorts in place |
sorted(lst) |
Returns a new sorted list |
reverse() |
Reverses in place |
index(x) |
Position of first x |
count(x) |
How many times x appears |
clear() |
Removes everything |
[1, 2, 5, 9] [5, 2, 9, 1] [9, 5, 2, 1] 0 1
Looping and Checking
for m in [85, 92]:
print(m)
print(92 in [85, 92])
print(sum([85, 92]) / 2, max([85, 92]))
85 92 True 88.5 92
List Comprehensions
squares = [x ** 2 for x in range(1, 6)]
evens = [x for x in range(10) if x % 2 == 0]
print(squares)
print(evens)
Explanation: [expression for item in iterable if condition] builds a list in one line. It is shorter and usually faster than a loop with append().
[1, 4, 9, 16, 25] [0, 2, 4, 6, 8]
Copying a List
a = [1, 2, 3]
b = a # same list
c = a.copy() # new list
a.append(4)
print(b, c)
[1, 2, 3, 4] [1, 2, 3]
copy.deepcopy(); copy() only copies the outer list.Nested Lists
matrix = [[1, 2, 3], [4, 5, 6]]
print(matrix[1][2])
6
Common Errors
| Problem | Cause and fix |
|---|---|
IndexError: list index out of range |
The index is beyond len(list) – 1. |
ValueError: list.remove(x): x not in list |
Check with if x in lst first. |
None after sort |
lst.sort() returns None. Use sorted(lst) if you need a result. |
Practice Exercises
- Remove duplicates from a list while keeping order.
- Find the second largest number.
- Flatten [[1,2],[3,4]] with a comprehension.
Interview Questions
Q: append vs extend?
append adds one item (even a list); extend adds each item of an iterable.
Q: sort() vs sorted()?
sort() changes the list in place and returns None; sorted() returns a new list.
Summary
Lists are ordered and mutable. Use append/insert/extend to add, remove/pop/del to delete, and comprehensions to build lists quickly.
Next: Python Tuples · Python Dictionary
Machine Learning Tutorials, Courses and Certifications