Python Lists – A Complete Guide for Beginners (with Examples and Output)

 

Python Lists – A Complete Guide for Beginners (with Examples and Output)

Published on Code with Py  |  Category: Python Basics  |  Reading time: ~15 min

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

  1. What is a List in Python?
  2. How to Create a List
  3. Accessing List Items – Indexing
  4. Negative Indexing
  5. List Slicing
  6. Changing List Items
  7. List is Mutable – What Does That Mean?
  8. Important List Methods
  9. Looping Through a List
  10. Nested Lists
  11. List Comprehension
  12. Real-Life Mini Projects
  13. Practice Problems
  14. FAQ

1. What is a List in Python?

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

  1. Items have a fixed position. The order you add them is the order they stay.

Mutable

  1. You can add, remove, or change items after the list is created.

Allows duplicates

  1. The same value can appear more than once in a list.

Mixed data types

  1. 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
Use 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.

ItemAppleBananaMangoGrapesOrange
Positive Index01234
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
If you try to access an index that does not exist — for example 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]
Just like strings, 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]
Compare this with a tuple: 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.

MethodWhat it doesExample
append(x)Adds x to the end of the listlist.append(5)
insert(i, x)Inserts x at position ilist.insert(1, "hi")
extend(list2)Adds all items of list2 to the listlist.extend([4,5])
remove(x)Removes first occurrence of xlist.remove(3)
pop(i)Removes and returns item at index ilist.pop(0)
clear()Removes all items from the listlist.clear()
sort()Sorts the list in ascending orderlist.sort()
reverse()Reverses the order of itemslist.reverse()
index(x)Returns index of first occurrence of xlist.index(5)
count(x)Counts how many times x appearslist.count(2)
copy()Returns a copy of the listnew = list.copy()
len(list)Returns total number of itemslen(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]
Use 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

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]
List comprehension is a very popular Python feature. It is shorter, faster, and more readable than a traditional for loop when building lists. Learn it well — it comes up a lot in interviews too.

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

  1. Create a list of 5 cities and print each one
  2. Print the first and last item of a list
  3. Find the length of a list without len()
  4. Check if a value exists in a list using in
  5. Merge two lists into one

List methods

  1. Add 3 items to a list using append()
  2. Insert a value at index 2
  3. Remove an item by value
  4. Sort a list in descending order
  5. Count occurrences of a value

Loops with lists

  1. Print all items with their index
  2. Find the sum of a number list
  3. Find the largest number without max()
  4. Count even numbers in a list
  5. Print only items greater than 50

List comprehension

  1. Create a list of squares from 1 to 10
  2. Get all even numbers from 1 to 50
  3. Filter only passing marks (>= 40)
  4. Convert all strings to uppercase
  5. Get lengths of words in a sentence
Post your solutions in the comments — let's review them together and learn from each other!

Quick Summary – What You Learned
  • 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 lists
  • remove() deletes by value, pop() deletes by index and returns the value
  • sort() sorts in place, reverse() flips the order
  • Use a for loop or enumerate() 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."


Previous        Next

Comments

Popular posts from this blog

Python Strings – A Complete Guide for Beginners (with Examples)

Python Control Flow Statements – Complete Guide with Real-Life Examples

Python Loops Explained – for Loop and while Loop with Examples and Output