📁 Lists¶
1. Definition and Initialization¶
In Python, a list is an ordered collection of items, which can be of any type and are enclosed in square brackets.
# list of integers
list1 = [1, 2, 3, 4, 5]
print(list1) # prints: [1, 2, 3, 4, 5]
# list of strings
list2 = ['apple', 'banana', 'cherry']
print(list2) # prints: ['apple', 'banana', 'cherry']
# mixed list
list3 = [1, 'apple', True, 3.14, [1, 2, 3]]
print(list3) # prints: [1, 'apple', True, 3.14, [1, 2, 3]]
[1, 2, 3, 4, 5] ['apple', 'banana', 'cherry'] [1, 'apple', True, 3.14, [1, 2, 3]]
2. Accessing List Items¶
You can access list items by referring to their index number. Python uses 0-based indexing.
list1 = [1, 2, 3, 4, 5]
print(list1[0]) # prints: 1
print(list1[2]) # prints: 3
# Negative indexing starts from the end.
print(list1[-1]) # prints: 5
1 3 5
3. Modifying List Items¶
You can modify list items by referring to their index number.
list1 = [1, 2, 3, 4, 5]
list1[0] = 10
print(list1) # prints: [10, 2, 3, 4, 5]
[10, 2, 3, 4, 5]
4. List Slicing¶
You can extract a part of a list using slicing. The syntax is list[start:stop:step]
.
5. List Methods¶
Python provides several methods to manipulate lists, like append()
, insert()
, remove()
, pop()
, sort()
, and many more.
list1 = [1, 2, 3, 4, 5]
# add an item to the end of the list
list1.append(6)
print(list1) # prints: [1, 2, 3, 4, 5, 6]
# add an item at a specified position
list1.insert(0, 0)
print(list1) # prints: [0, 1, 2, 3, 4, 5, 6]
# remove a specified item
list1.remove(0)
print(list1) # prints: [1, 2, 3, 4, 5, 6]
# remove an item at a specified position
list1.pop(0)
print(list1) # prints: [2, 3, 4, 5, 6]
# sort the list
list1.sort(reverse=True)
print(list1) # prints: [6, 5, 4, 3, 2]
[1, 2, 3, 4, 5, 6] [0, 1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [2, 3, 4, 5, 6] [6, 5, 4, 3, 2]
6. List Comprehensions¶
List comprehensions provide a concise way to create lists. It consists of brackets containing an expression followed by a for statement, optionally followed by for or if clauses.
# create a list of squares for numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # prints: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# create a list of even numbers from the above list
evens = [x for x in squares if x % 2 == 0]
print(evens) # prints: [0, 4, 16, 36, 64]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [0, 4, 16, 36, 64]
7. Nested Lists¶
A list can contain other lists. This is called a nested list.
nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested) # prints: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested[0]) # prints: [1, 2, 3]
print(nested[0][1]) # prints: 2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] [1, 2, 3] 2
8. Length of a List¶
You can get the number of items in a list with the len()
function.
list1 = [1, 2, 3, 4, 5]
print(len(list1)) # prints: 5
5