Lists in Python
In Python, lists are one of the most versatile and commonly used data structures.
They are ordered, mutable (modifiable), and can store elements of different data types.
Key Features of Lists
• Ordered: Elements maintain their insertion order.
• Mutable: You can modify, add, or remove elements.
• Heterogeneous: Can store elements of different types (e.g., integers,
strings, objects).
Creating a List
Empty list
my_list = [ ]
List with elements
numbers = [1, 2, 3, 4]
mixed = [1, "hello", 3.14, True]
Accessing Elements
Indexing: Access elements using their position (starting from 0).
Negative Indexing: Access elements from the end (-1 is the last element).
numbers = [10, 20, 30, 40]
Accessing elements
print(numbers[0]) # Output: 10
print(numbers[-1]) # Output: 40
Modifying a List
Changing an element
numbers[1] = 25 #Output: [10, 25, 30, 40]
Adding elements
numbers.append(50) #Output: [10, 25, 30, 40, 50]
numbers.insert(2, 15) #Output: [10, 25, 15, 30, 40, 50]
Removing elements
numbers.remove(30) #Output: [10, 25, 15, 40, 50]
popped = numbers.pop() # Removes last element, popped = 50
List Operations
Slicing: Extract sublists.
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
# Output: [20, 30, 40]
Concatenation: Combine lists.
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2
#Output: [1, 2, 3, 4]
Repetition: Repeat elements.
repeated = [1, 2] * 3
#Output: [1, 2, 1, 2, 1, 2]
Useful Methods Method Description
append(x) - Adds an element to the end of the list.
extend(iterable) - Adds all elements of an iterable.
insert(i, x) - Inserts an element at index i.
remove(x) - Removes the first occurrence of x.
pop([i]) - Removes and returns the element at i.
sort() - Sorts the list in ascending order.
reverse() - Reverses the list. List Comprehension
Example: Create a list of squares
squares = [x**2 for x in range(5)]
#Output: [0, 1, 4, 9, 16]