Lists are one of the most commonly used data structures in Python. They allow you to store ordered collections of items that can be modified.
1) What is a List?
A list is an ordered collection of items, enclosed in square brackets [ ].
Lists can contain items of different types: integers, strings, floats, or even other lists.
# Example of a list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["Alice", 25, True, 3.14]
nested = [[1, 2], [3, 4]]
2) Accessing Elements
Use indexing to access list elements. Python uses 0-based indexing.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[2]) # cherry
print(fruits[-1]) # cherry (last element)
Note: Using an index out of range gives IndexError.
3) Adding Elements
You can add items to a list using append(), insert(), or extend().
fruits = ["apple", "banana"]
fruits.append("cherry") # Add at the end
fruits.insert(1, "orange") # Add at specific index
fruits.extend(["mango", "kiwi"]) # Add multiple items
print(fruits)
# Output: ['apple', 'orange', 'banana', 'cherry', 'mango', 'kiwi']
4) Removing Elements
You can remove elements using remove(), pop(), or del.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove last element
del fruits[0] # Remove by index
print(fruits)
# Output: []
Common Mistakes:
- Using
remove()on an element that doesn’t exist →ValueError - Accessing or deleting index out of range →
IndexError
5) Slicing and Iterating
Lists can be sliced to access a range of elements and iterated with loops.
fruits = ["apple", "banana", "cherry", "mango"]
# Slicing
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
print(fruits[::2]) # ['apple', 'cherry']
# Iterating
for fruit in fruits:
print(fruit)
6) Common List Methods
append()– Add item to endinsert()– Add item at indexextend()– Add multiple itemsremove()– Remove item by valuepop()– Remove item by index or last elementsort()– Sort list in ascending orderreverse()– Reverse the listindex()– Find index of itemcount()– Count occurrences of item
7) Common Mistakes
- Using parentheses instead of brackets →
fruits("apple") ❌ - Trying to access index out of range →
fruits[10] ❌ - Confusing
append()andextend() - Modifying a list while iterating over it → unexpected behavior
No comments:
Post a Comment