Python Lists – A Complete Guide for Beginners (with Examples and Output)
Python Lists – A Complete Guide for Beginners (with Examples and Output)
Imagine you want to store the marks of 30 students. Would you create 30 separate variables? That would be very messy. Python gives you a much better solution — the List. A list lets you store multiple values in a single variable, access them easily, and perform powerful operations on them. In this complete guide, you will learn everything about Python lists — from creating them to using all major methods — with simple examples and clear outputs at every step.
Table of Contents
- What is a List in Python?
- How to Create a List
- Accessing List Items – Indexing
- Negative Indexing
- List Slicing
- Changing List Items
- List is Mutable – What Does That Mean?
- Important List Methods
- Looping Through a List
- Nested Lists
- List Comprehension
- Real-Life Mini Projects
- Practice Problems
- FAQ
1. What is a List in Python?
A list is a collection that stores multiple values in a single variable. Think of it like a shopping list on paper — you write multiple items one after another and refer to the whole list by one name.
In Python, a list has four important properties:
Ordered
- Items have a fixed position. The order you add them is the order they stay.
Mutable
- You can add, remove, or change items after the list is created.
Allows duplicates
- The same value can appear more than once in a list.
Mixed data types
- A single list can hold integers, strings, floats, and even other lists.
2. How to Create a List
A list is created using square brackets [ ]. Items inside the list are separated by commas.
# Empty list empty = [] # List of numbers marks = [80, 85, 90, 78, 92] # List of strings fruits = ["Apple", "Banana", "Mango"] # List with mixed data types student = ["Rohan", 21, 85.5, True] # List with duplicate values numbers = [1, 2, 2, 3, 3, 3] print(marks) print(fruits) print(student) print(len(marks)) # Number of items
[80, 85, 90, 78, 92] ['Apple', 'Banana', 'Mango'] ['Rohan', 21, 85.5, True] 5
len(list) to find the total number of items in a list. This is one of the most frequently used functions when working with lists.3. Accessing List Items – Indexing
Each item in a list has a position number called an index. Python indexing starts from 0 — the first item is at index 0, the second at index 1, and so on. Use square brackets [ ] with the index number to access an item.
| Item | Apple | Banana | Mango | Grapes | Orange |
|---|---|---|---|---|---|
| Positive Index | 0 | 1 | 2 | 3 | 4 |
| Negative Index | -5 | -4 | -3 | -2 | -1 |
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"] print(fruits[0]) # First item print(fruits[2]) # Third item print(fruits[4]) # Last item
Apple Mango Orange
fruits[10] in a 5-item list — Python raises an IndexError. Always make sure the index is within range.4. Negative Indexing
Python allows negative indexing to access items from the end of the list. -1 is the last item, -2 is the second last, and so on. This is very useful when you do not know the length of the list.
fruits = ["Apple", "Banana", "Mango", "Grapes", "Orange"] print(fruits[-1]) # Last item print(fruits[-2]) # Second last print(fruits[-5]) # First item (same as index 0)
Orange Grapes Apple
5. List Slicing
Slicing lets you extract a portion of a list — not just one item, but a range of items. The syntax is list[start:stop:step]. The stop index is not included in the result.
marks = [55, 60, 72, 85, 90, 78] print(marks[1:4]) # Index 1 to 3 print(marks[:3]) # First 3 items print(marks[3:]) # From index 3 to end print(marks[::2]) # Every second item print(marks[::-1]) # Reverse the list
[60, 72, 85] [55, 60, 72] [85, 90, 78] [55, 72, 90] [78, 90, 85, 72, 60, 55]
list[::-1] reverses a list. This is commonly asked in Python coding interviews — remember it!6. Changing List Items
Since lists are mutable, you can change the value of any item by accessing it through its index and assigning a new value.
fruits = ["Apple", "Banana", "Mango"] print("Before:", fruits) fruits[1] = "Grapes" # Change second item print("After:", fruits)
Before: ['Apple', 'Banana', 'Mango'] After: ['Apple', 'Grapes', 'Mango']
# Change a range of items using slicing numbers = [1, 2, 3, 4, 5] numbers[1:3] = [20, 30] print(numbers)
[1, 20, 30, 4, 5]
7. List is Mutable – What Does That Mean?
Mutable means the list can be changed after it is created. You can add items, remove items, or modify existing items. This is different from a tuple, which cannot be changed once created.
my_list = [10, 20, 30] my_list[0] = 99 # Change item – works fine my_list.append(40) # Add item – works fine my_list.remove(20) # Remove item – works fine print(my_list)
[99, 30, 40]
my_tuple = (10, 20, 30) — if you try my_tuple[0] = 99, Python raises a TypeError. Tuples are immutable, lists are not.8. Important List Methods
Python provides many built-in methods to work with lists. Here are all the important ones every beginner must know.
| Method | What it does | Example |
|---|---|---|
append(x) | Adds x to the end of the list | list.append(5) |
insert(i, x) | Inserts x at position i | list.insert(1, "hi") |
extend(list2) | Adds all items of list2 to the list | list.extend([4,5]) |
remove(x) | Removes first occurrence of x | list.remove(3) |
pop(i) | Removes and returns item at index i | list.pop(0) |
clear() | Removes all items from the list | list.clear() |
sort() | Sorts the list in ascending order | list.sort() |
reverse() | Reverses the order of items | list.reverse() |
index(x) | Returns index of first occurrence of x | list.index(5) |
count(x) | Counts how many times x appears | list.count(2) |
copy() | Returns a copy of the list | new = list.copy() |
len(list) | Returns total number of items | len(list) |
append() and insert()
fruits = ["Apple", "Banana"] fruits.append("Mango") # Add to end print(fruits) fruits.insert(1, "Grapes") # Add at index 1 print(fruits)
['Apple', 'Banana', 'Mango'] ['Apple', 'Grapes', 'Banana', 'Mango']
remove() and pop()
numbers = [10, 20, 30, 40, 50] numbers.remove(30) # Remove by value print(numbers) removed = numbers.pop(0) # Remove by index, returns value print(f"Removed: {removed}") print(numbers)
[10, 20, 40, 50] Removed: 10 [20, 40, 50]
remove() when you know the value. Use pop() when you know the index. pop() also returns the removed value so you can use it.sort() and reverse()
marks = [85, 60, 92, 45, 78] marks.sort() print("Ascending:", marks) marks.sort(reverse=True) print("Descending:", marks) marks.reverse() print("Reversed:", marks)
Ascending: [45, 60, 78, 85, 92] Descending: [92, 85, 78, 60, 45] Reversed: [45, 60, 78, 85, 92]
extend(), count(), and index()
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print("Extended:", list1) nums = [1, 2, 2, 3, 2, 4] print("Count of 2:", nums.count(2)) print("Index of 3:", nums.index(3))
Extended: [1, 2, 3, 4, 5, 6] Count of 2: 3 Index of 3: 3
9. Looping Through a List
You can use a for loop to go through every item in a list one by one. This is one of the most common operations in Python programming.
Basic loop
fruits = ["Apple", "Banana", "Mango"] for fruit in fruits: print(fruit)
Apple Banana Mango
Loop with index using enumerate()
fruits = ["Apple", "Banana", "Mango"] for index, fruit in enumerate(fruits): print(f"{index + 1}. {fruit}")
1. Apple 2. Banana 3. Mango
Loop to find sum and average
marks = [80, 85, 90, 78, 92] total = 0 for m in marks: total += m average = total / len(marks) print(f"Total: {total}") print(f"Average: {average}")
Total: 425 Average: 85.0
10. Nested Lists
A nested list is a list inside another list. This is useful for storing table-like data such as a matrix, student records, or a timetable.
# 2D list – like a table with rows and columns matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[0]) # First row print(matrix[1][2]) # Row 2, Column 3 print(matrix[2][0]) # Row 3, Column 1
[1, 2, 3] 6 7
# Print full matrix using nested loop for row in matrix: for item in row: print(item, end=" ") print()
1 2 3 4 5 6 7 8 9
11. List Comprehension
List comprehension is a short and elegant way to create a new list from an existing one — all in a single line. It replaces a for loop that builds a list step by step.
# Normal way – using a for loop squares = [] for i in range(1, 6): squares.append(i ** 2) print(squares) # List comprehension – one clean line squares = [i ** 2 for i in range(1, 6)] print(squares)
[1, 4, 9, 16, 25] [1, 4, 9, 16, 25]
List comprehension with condition
# Get only even numbers from 1 to 20 evens = [i for i in range(1, 21) if i % 2 == 0] print(evens) # Get only passing marks (>= 40) marks = [35, 80, 22, 90, 45, 38] passing = [m for m in marks if m >= 40] print(passing)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] [80, 90, 45]
12. Real-Life Mini Projects
Project 1 – Student Mark Sheet
students = ["Rohan", "Priya", "Arjun", "Meera"] marks = [85, 92, 67, 78] print("--- Mark Sheet ---") for i in range(len(students)): status = "Pass" if marks[i] >= 40 else "Fail" print(f"{students[i]:10} | {marks[i]} | {status}") print(f"\nHighest: {max(marks)}") print(f"Lowest: {min(marks)}") print(f"Average: {sum(marks)/len(marks):.1f}")
--- Mark Sheet --- Rohan | 85 | Pass Priya | 92 | Pass Arjun | 67 | Pass Meera | 78 | Pass Highest: 92 Lowest: 67 Average: 80.5
Project 2 – Shopping Cart
cart = [] cart.append("Rice") cart.append("Dal") cart.append("Oil") cart.append("Sugar") print("Your Cart:") for i, item in enumerate(cart, 1): print(f" {i}. {item}") cart.remove("Dal") print(f"\nAfter removing Dal: {cart}") print(f"Total items: {len(cart)}")
Your Cart: 1. Rice 2. Dal 3. Oil 4. Sugar After removing Dal: ['Rice', 'Oil', 'Sugar'] Total items: 3
13. Practice Problems
Try solving each problem on your own before looking for hints. Testing with different inputs helps you understand the logic deeply.
Basic list operations
- Create a list of 5 cities and print each one
- Print the first and last item of a list
- Find the length of a list without len()
- Check if a value exists in a list using in
- Merge two lists into one
List methods
- Add 3 items to a list using append()
- Insert a value at index 2
- Remove an item by value
- Sort a list in descending order
- Count occurrences of a value
Loops with lists
- Print all items with their index
- Find the sum of a number list
- Find the largest number without max()
- Count even numbers in a list
- Print only items greater than 50
List comprehension
- Create a list of squares from 1 to 10
- Get all even numbers from 1 to 50
- Filter only passing marks (>= 40)
- Convert all strings to uppercase
- Get lengths of words in a sentence
- A list stores multiple values in one variable using square brackets
[ ] - Lists are ordered, mutable, and allow duplicate values
- Indexing starts at 0; negative indexing starts at -1 from the end
- Slicing
list[start:stop:step]extracts a portion of the list append()adds to end,insert()adds at a position,extend()merges listsremove()deletes by value,pop()deletes by index and returns the valuesort()sorts in place,reverse()flips the order- Use a
forloop orenumerate()to iterate through a list - Nested lists store table-like data — access with
list[row][col] - List comprehension creates a new list from an existing one in one clean line
Frequently Asked Questions (FAQ)
Q1. What is the difference between append() and extend() in Python?
append() adds a single item to the end of the list. extend() adds all items from another list (or iterable) to the end. So list.append([4,5]) adds the entire sub-list as one item, while list.extend([4,5]) adds 4 and 5 as separate items.
Q2. What is the difference between remove() and pop()?
remove(x) deletes the first occurrence of the value x from the list. pop(i) removes and returns the item at index i. Use remove when you know the value, use pop when you know the position.
Q3. Can a Python list store different data types?
Yes. A single Python list can hold integers, floats, strings, booleans, and even other lists — all at the same time. For example: data = ["Rohan", 21, 85.5, True] is perfectly valid.
Q4. What is the difference between a list and a tuple?
Both store ordered collections of values. The key difference is mutability — lists are mutable (you can change them after creation), while tuples are immutable (once created, they cannot be changed). Lists use [ ] and tuples use ( ).
Q5. How do I check if an item exists in a list?
Use the in keyword. For example: if "Apple" in fruits: returns True if "Apple" is in the list. You can also use not in to check absence.
Q6. What is list comprehension and when should I use it?
List comprehension is a concise way to create a new list from an existing one in a single line. Use it when you need to transform or filter a list — it is faster and more readable than a traditional for loop for simple operations.
Found this post helpful? Share it with someone learning Python. Drop your practice solutions in the comments — happy to review them!
"Lists are the most versatile data structure in Python. Master them and everything else becomes easier."
Comments
Post a Comment