Python Lists Explained: Methods, Examples & Operations (Beginner Guide)
π Python Lists Explained
Complete Guide
Create · Access · Methods · Loop · Sort · Slice · Comprehension · Real-Life
A list in Python is an ordered collection used to store multiple items in a single variable. Lists can hold items of any data type — integers, strings, floats, booleans, or even other lists. Lists are mutable, meaning you can change, add, or remove items after creation. They are one of the most commonly used and powerful data structures in Python.
fruits = ["apple", "banana", "mango"] numbers = [1, 2, 3, 4, 5] mixed = ["Ali", 18, True, 3.14] print(fruits) print(numbers)
[1, 2, 3, 4, 5]
You can create a list in Python using square brackets [ ] with items separated by commas. You can also create an empty list and add items later. Python also provides the list() constructor to create a list from other sequences.
# Empty list my_list = [] # List with values colors = ["red", "green", "blue"] # Using list() constructor nums = list((1, 2, 3)) # List from a string letters = list("Python") print(colors) # ['red', 'green', 'blue'] print(letters) # ['P','y','t','h','o','n']
[] is valid in Python. You can add items to it later using append().Python lists are very flexible — they can store different types of data. Here are the common types of lists based on the data they hold.
| Type | Example |
|---|---|
| Integer list | [1, 2, 3, 4, 5] |
| Float list | [1.1, 2.2, 3.3] |
| String list | ["apple", "mango"] |
| Boolean list | [True, False, True] |
| Mixed list | ["Ali", 18, True, 3.14] |
| Nested list | [[1,2], [3,4], [5,6]] |
| Empty list | [] |
student = ["Ali", 18, True, 85.5] print(student) # ['Ali', 18, True, 85.5]
Each item in a list has an index (position number) starting from 0. You can access items using their index in square brackets. Python also supports negative indexing — -1 is the last item. Slicing lets you get a range of items.
fruits = ["apple", "banana", "mango", "grape"] print(fruits[0]) # apple (first) print(fruits[2]) # mango print(fruits[-1]) # grape (last) print(fruits[-2]) # mango
nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] print(nums[:3]) # [10, 20, 30] print(nums[2:]) # [30, 40, 50] print(nums[::-1]) # [50,40,30,20,10]
Python provides many built-in methods to work with lists. These methods make it easy to add, remove, find, sort, and manipulate list items.
| Method | Description | Example |
|---|---|---|
| append() | Add item at end | lst.append(5) |
| insert() | Add at position | lst.insert(1, "x") |
| extend() | Add multiple items | lst.extend([4,5]) |
| remove() | Remove by value | lst.remove("a") |
| pop() | Remove by index | lst.pop(0) |
| clear() | Remove all items | lst.clear() |
| sort() | Sort in order | lst.sort() |
| reverse() | Reverse the list | lst.reverse() |
| copy() | Copy the list | lst2 = lst.copy() |
| count() | Count occurrences | lst.count(3) |
| index() | Find position | lst.index("a") |
| len() | Get list length | len(lst) |
Python provides three main ways to add items to a list — append() adds one item at the end, insert() adds at a specific position, and extend() adds multiple items at once from another list or sequence.
▶ append() — add one item at end:fruits = ["apple", "banana"] fruits.append("mango") print(fruits) # ['apple', 'banana', 'mango']
fruits = ["apple", "banana"] fruits.insert(1, "orange") print(fruits) # ['apple', 'orange', 'banana']
fruits = ["apple"] fruits.extend(["grape", "mango"]) print(fruits) # ['apple', 'grape', 'mango']
Python provides three main ways to remove items — remove() removes by value, pop() removes by index (and returns the removed item), and clear() removes all items from the list at once.
▶ remove() — remove by value:fruits = ["apple", "banana", "mango"] fruits.remove("banana") print(fruits) # ['apple', 'mango']
fruits = ["apple", "banana", "mango"] removed = fruits.pop(1) print(removed) # banana print(fruits) # ['apple', 'mango']
fruits = ["apple", "banana"] fruits.clear() print(fruits) # []
Since lists are mutable, you can update (change) any item by accessing it using its index and assigning a new value. You can update a single item or update a range of items using slicing.
▶ Update single item:fruits = ["apple", "banana", "mango"] fruits[1] = "orange" print(fruits) # ['apple', 'orange', 'mango']
nums = [1, 2, 3, 4, 5] nums[1:3] = [20, 30] print(nums) # [1, 20, 30, 4, 5]
list[index] += value to update numerically — e.g. scores[0] += 10You can loop through a list using a for loop to access and process each item one by one. You can also use enumerate() to get both the index and the value at the same time during iteration.
▶ Basic for loop:fruits = ["apple", "banana", "mango"] for fruit in fruits: print(fruit)
banana
mango
fruits = ["apple", "banana", "mango"] for i, fruit in enumerate(fruits): print(i, "-", fruit)
1 - banana
2 - mango
The len() function returns the total number of items in a list. It is very commonly used to find how many elements are in a list, to loop through a list by index, or to check if a list is empty.
fruits = ["apple", "banana", "mango"] print(len(fruits)) # 3 nums = [10, 20, 30, 40] print(len(nums)) # 4 # Check if empty if len(fruits) == 0: print("List is empty") else: print("List has", len(fruits), "items")
4
List has 3 items
Python lists support two useful operations — concatenation using the + operator to combine two lists, and repetition using the * operator to repeat a list a given number of times. These make creating and merging lists very easy.
▶ Concatenation ( + ):a = [1, 2, 3] b = [4, 5, 6] c = a + b print(c) # [1, 2, 3, 4, 5, 6]
x = [0, 1] print(x * 3) # [0, 1, 0, 1, 0, 1] # Useful for creating filled lists zeros = [0] * 5 print(zeros) # [0, 0, 0, 0, 0]
Python provides sort() to sort a list in ascending or descending order, and reverse() to flip the list order. The sorted() built-in function returns a new sorted list without changing the original.
▶ sort() — ascending order:nums = [3, 1, 4, 1, 5, 9, 2] nums.sort() print(nums) # [1, 1, 2, 3, 4, 5, 9]
nums = [3, 1, 4, 9, 2] nums.sort(reverse=True) print(nums) # [9, 4, 3, 2, 1]
items = ["a", "b", "c", "d"] items.reverse() print(items) # ['d', 'c', 'b', 'a']
sort() modifies the original list. Use sorted(list) if you want a new sorted copy without changing the original.You cannot simply copy a list by writing list2 = list1 — this just creates a reference to the same list. Changes in one will affect the other. To make a true independent copy, use the copy() method or list() constructor or slicing [:].
a = [1, 2, 3] b = a # b points to same list! b.append(4) print(a) # [1, 2, 3, 4] ← a changed!
a = [1, 2, 3] # Method 1 — copy() b = a.copy() # Method 2 — list() c = list(a) # Method 3 — slicing d = a[:] b.append(99) print(a) # [1, 2, 3] ← unchanged! print(b) # [1, 2, 3, 99]
A nested list is a list that contains other lists as its elements. This is useful for representing tables, matrices, grids, and multi-dimensional data. You access elements of a nested list using multiple indexes — first the outer index, then the inner index.
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[0]) # [1, 2, 3] print(matrix[1][2]) # 6 (row 1, col 2) print(matrix[2][0]) # 7 (row 2, col 0)
for row in matrix: for item in row: print(item, end=" ") print()
4 5 6
7 8 9
List comprehension is a short, elegant way to create a new list from an existing sequence in just one line. It replaces a for loop that builds a list. It is faster, more readable, and very commonly used in Python.
squares = [] for i in range(1, 6): squares.append(i ** 2) print(squares) # [1, 4, 9, 16, 25]
squares = [i ** 2 for i in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] # With condition — even numbers only evens = [i for i in range(1, 11) if i % 2 == 0] print(evens) # [2, 4, 6, 8, 10]
| Feature | List | Tuple |
|---|---|---|
| Syntax | [ ] | ( ) |
| Mutable? | Yes — can change | No — cannot change |
| Speed | Slower | Faster |
| Methods | Many (append etc.) | Only 2 (count, index) |
| Use when | Data may change | Data is fixed |
| Example | [1, 2, 3] | (1, 2, 3) |
my_list = [1, 2, 3] my_tuple = (1, 2, 3) my_list[0] = 99 # ✅ works # my_tuple[0] = 99 ← TypeError!
lst = [1, 2, 3] print(lst[5]) # IndexError! # Fix: use index 0, 1, or 2 only
lst = ["a", "b", "c"] lst.remove("z") # ValueError! # Fix: check first → if "z" in lst:
a = [1, 2] b = a # same object! b.append(3) print(a) # [1,2,3] ← surprise! # Fix: b = a.copy()
# ❌ Don't remove while iterating lst = [1, 2, 3, 4] for x in lst: lst.remove(x) # unpredictable! # ✅ Fix: loop over a copy for x in lst[:]: lst.remove(x)
cart = ["milk", "bread", "eggs"] cart.append("butter") print("Items:", len(cart)) for item in cart: print("-", item)
- milk
- bread
- eggs
- butter
marks = [85, 90, 78, 92, 88] avg = sum(marks) / len(marks) print("Average:", avg) print("Highest:", max(marks)) print("Lowest :", min(marks))
Highest: 92
Lowest : 78
todos = ["Study Python", "Exercise"] todos.append("Read book") todos.remove("Exercise") print("My Todos:") for i, t in enumerate(todos, 1): print(f"{i}. {t}")
1. Study Python
2. Read book
Python lists are powerful, flexible, and essential for every programmer. They allow you to store, access, update, sort, and process collections of data with ease. Mastering lists is one of the most important steps in learning Python.
Practice creating lists, using all the methods, looping through them, and applying list comprehension. Once you master lists, other data structures like tuples, sets, and dictionaries will become much easier to understand!
| Topic | Key Point |
|---|---|
| Create | [ ] or list() constructor |
| Access | Index [0], Negative [-1], Slice [:] |
| Add | append(), insert(), extend() |
| Remove | remove(), pop(), clear() |
| Update | list[index] = new_value |
| Sort | sort(), reverse(), sorted() |
| Copy | copy(), list(), [:] |
| Loop | for item in list |
| Length | len(list) |
| Comprehension | [expr for i in seq if cond] |
Comments
Post a Comment