A list is a built-in data structure in Python that is ordered, mutable (changeable), and allows duplicate values.
✅ Lists can store multiple data items in a single variable.
Feature | Description |
---|---|
Ordered | Items have a defined order (index-based) |
Mutable | Items can be changed after creation |
Duplicates | Allows repeated values |
Heterogeneous | Can contain different data types |
# Creating a list
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, "Hello", 3.14, True]
empty_list = []
print(my_list[0]) # Output: 1 (indexing starts from 0)
print(my_list[-1]) # Output: 5 (last element using negative index)
my_list[2] = 10
print(my_list) # Output: [1, 2, 10, 4, 5]
my_list.append(6) # Add at end
my_list.insert(1, "Hi") # Insert at index 1
my_list.remove(10) # Remove value 10
my_list.pop() # Remove last item
my_list.pop(2) # Remove item at index 2
my_list.sort() # Sort list
my_list.reverse() # Reverse list
my_list.index(4) # Find index of 4
len(my_list) # Length of list
for item in my_list:
print(item)
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Lists can contain other lists:
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][0]) # Output: 3
Function | Purpose |
---|---|
len() |
Length of list |
sum() |
Sum of all numeric elements |
min() |
Minimum element |
max() |
Maximum element |
list() |
Convert iterable to list |
Think of a list like a shopping basket – you can add, remove, or modify items any time, and it can contain different types of things: fruits, bottles, bills, etc.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry', 'orange']