A list is one of the most versatile and commonly used data structures in Python. It is an ordered, mutable collection of items that can store elements of different data types.
Lists are defined using square brackets [] with elements separated by commas.
# Empty list
empty_list = []
# List of integers
numbers = [10, 20, 30, 40]
# List of mixed data types
mixed = [1, 'hello', 3.14, True]
# List of strings
fruits = ['apple', 'banana', 'cherry']
| Property | Description |
|---|---|
| Ordered | Elements maintain their insertion order |
| Mutable | Elements can be changed after creation |
| Indexed | Each element has a numeric index |
| Heterogeneous | Can store different data types |
Python uses zero-based indexing — the first element is at index 0.
fruits = ['apple', 'banana', 'cherry']
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[2]) # Output: cherry
Negative indices count from the end of the list. Index -1 is the last element.
fruits = ['apple', 'banana', 'cherry']
print(fruits[-1]) # Output: cherry
print(fruits[-2]) # Output: banana
Because lists are mutable, you can change any element by assigning a new value to its index.
L = [1, 2, 3]
L[1] = 5
print(L) # Output: [1, 5, 3]
Slicing extracts a sub-list using the syntax:
list[start:stop:step]
start — index to begin (inclusive)stop — index to end (exclusive)step — interval between elements (default is 1)L = [0, 1, 2, 3, 4, 5]
print(L[1:4]) # Output: [1, 2, 3]
print(L[0:6:2]) # Output: [0, 2, 4]
print(L[:3]) # Output: [0, 1, 2]
print(L[3:]) # Output: [3, 4, 5]
append() — Add to EndL = [1, 2, 3]
L.append(4)
print(L) # Output: [1, 2, 3, 4]
insert() — Add at Specific IndexL = [1, 2, 3]
L.insert(1, 10) # Insert 10 at index 1
print(L) # Output: [1, 10, 2, 3]
pop() — Remove by IndexL = [1, 2, 3, 4]
L.pop(2) # Removes element at index 2
print(L) # Output: [1, 2, 4]
remove() — Remove by ValueL = [1, 2, 3, 2]
L.remove(2) # Removes first occurrence of 2
print(L) # Output: [1, 3, 2]
len() — Length of ListA = [10, 20, 30, 40]
print(len(A)) # Output: 4
sort() — Sort the ListL = [3, 1, 4, 1, 5]
L.sort()
print(L) # Output: [1, 1, 3, 4, 5]
Lists are commonly used with loops to process each element — this directly supports translating repetition algorithms into Python.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
range() with Listsnumbers = [10, 20, 30, 40, 50]
for i in range(len(numbers)):
print(f"Index {i}: {numbers[i]}")
A common algorithmic pattern is to build a list by appending elements inside a loop:
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares) # Output: [1, 4, 9, 16, 25]