Paramclasses Academy - Blog

Tutorials Details

←
Post 10 of 20
→

Python Lists & Tuples: Methods, Indexing, Slicing & Examples

Python Lists & Tuples: Methods, Indexing, Slicing & Examples

October 17, 2026

Python Lists & Tuples: Methods, Indexing, Slicing & Examples

1. Introduction to Python Lists and Tuples

Python provides several data structures for storing collections of values. Two important data structures are Lists and Tuples.

A List is an ordered, mutable collection that allows duplicate values.

A Tuple is an ordered, immutable collection that also allows duplicate values.

Both can store strings, numbers, Boolean values, and other Python objects.

Example

# Python List
fruits = ["Apple", "Banana", "Mango"]

# Python Tuple
colors = ("Red", "Green", "Blue")

print(fruits)
print(colors)

Output:

['Apple', 'Banana', 'Mango']
('Red', 'Green', 'Blue')

2. Python Lists

A list stores multiple items in a single variable. Lists are written using square brackets [].

Creating a List

numbers = [10, 20, 30, 40, 50]
names = ["Rahul", "Amit", "Priya"]
mixed_data = ["Python", 25, 85.5, True]

print(numbers)
print(names)
print(mixed_data)

Output:

[10, 20, 30, 40, 50]
['Rahul', 'Amit', 'Priya']
['Python', 25, 85.5, True]

Creating an Empty List

tasks = []
print(tasks)

Output:

[]

You can add items to this list later.

3. Accessing List Items Using Indexing

List indexing allows you to access individual items by their positions. Python uses zero-based indexing.

  • First item: index 0

  • Second item: index 1

  • Last item: index -1

Example

fruits = ["Apple", "Banana", "Mango", "Orange"]

print(fruits[0])
print(fruits[2])
print(fruits[-1])

Output:

Apple
Mango
Orange

Accessing an index that does not exist raises an IndexError.

4. List Slicing

List slicing extracts a portion of a list.

Syntax

list_name[start:stop:step]

The stop index is excluded from the result.

Example 1: Basic Slicing

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])
print(numbers[:3])
print(numbers[2:])

Output:

[20, 30, 40]
[10, 20, 30]
[30, 40, 50]

Example 2: Reverse a List

numbers = [1, 2, 3, 4, 5]

print(numbers[::-1])

Output:

[5, 4, 3, 2, 1]

Slicing creates a new list containing the selected items.

5. Modifying List Items

Lists are mutable, so you can change their items after creation.

Updating an Item

fruits = ["Apple", "Banana", "Mango"]

fruits[1] = "Orange"

print(fruits)

Output:

['Apple', 'Orange', 'Mango']

Updating Multiple Items with Slicing

numbers = [10, 20, 30, 40]

numbers[1:3] = [200, 300]

print(numbers)

Output:

[10, 200, 300, 40]

6. Adding Items to a List

Python provides methods to add new items to a list.

append()

Adds one item to the end of a list.

fruits = ["Apple", "Banana"]

fruits.append("Mango")

print(fruits)

Output: ['Apple', 'Banana', 'Mango']

insert()

Inserts an item at a specified position.

fruits = ["Apple", "Mango"]

fruits.insert(1, "Banana")

print(fruits)

Output: ['Apple', 'Banana', 'Mango']

extend()

Adds items from another iterable to the end of a list.

numbers = [1, 2, 3]

numbers.extend([4, 5, 6])

print(numbers)

Output: [1, 2, 3, 4, 5, 6]

Difference: append() adds its argument as one item, while extend() adds each item from the iterable.

numbers = [1, 2]
numbers.append([3, 4])

print(numbers)

Output: [1, 2, [3, 4]]

7. Removing Items from a List

remove()

Removes the first matching value.

fruits = ["Apple", "Banana", "Mango"]

fruits.remove("Banana")

print(fruits)

Output: ['Apple', 'Mango']

If the value does not exist, remove() raises a ValueError.

pop()

Removes and returns an item by index. If no index is supplied, it removes the last item.

numbers = [10, 20, 30, 40]

removed = numbers.pop()

print("Removed:", removed)
print("List:", numbers)

Output:

Removed: 40
List: [10, 20, 30]

del Statement

Deletes an item or a slice.

numbers = [10, 20, 30, 40]

del numbers[1]

print(numbers)

Output: [10, 30, 40]

clear()

Removes all items while keeping the list itself.

numbers = [1, 2, 3]

numbers.clear()

print(numbers)

Output: []

8. Important Python List Methods

Method Purpose
append() Adds one item at the end
extend() Adds items from an iterable
insert() Inserts an item at a position
remove() Removes the first matching value
pop() Removes and returns an item
clear() Removes all items
index() Returns the index of the first matching value
count() Counts occurrences of a value
sort() Sorts the list in place
reverse() Reverses the list in place
copy() Creates a shallow copy

Example

numbers = [30, 10, 20, 10]

print(numbers.count(10))
print(numbers.index(20))

numbers.sort()
print(numbers)

numbers.reverse()
print(numbers)

Output:

2
2
[10, 10, 20, 30]
[30, 20, 10, 10]

Important: Methods such as sort(), reverse(), append(), and remove() modify the list in place. They normally return None, not the updated list.

9. Sorting Lists

Use sort() to sort a list in place.

Ascending Order

numbers = [50, 10, 40, 20, 30]

numbers.sort()

print(numbers)

Output: [10, 20, 30, 40, 50]

Descending Order

numbers = [50, 10, 40, 20, 30]

numbers.sort(reverse=True)

print(numbers)

Output: [50, 40, 30, 20, 10]

Using sorted()

The sorted() function returns a new sorted list and leaves the original iterable unchanged.

numbers = [30, 10, 20]

result = sorted(numbers)

print("Original:", numbers)
print("Sorted:", result)

Output:

Original: [30, 10, 20]
Sorted: [10, 20, 30]

10. Useful List Operations

Python provides built-in functions and operators for working with lists.

numbers = [10, 20, 30, 40, 50]

print(len(numbers))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
print(20 in numbers)

Output:

5
10
50
150
True
  • len() returns the number of items.

  • min() returns the smallest item.

  • max() returns the largest item.

  • sum() adds numeric items.

  • in checks whether a value is present.

11. Looping Through a List

A for loop lets you process each item in a list.

Example 1: Display Every Item

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

Output:

Apple
Banana
Mango

Example 2: Calculate the Total

prices = [100, 250, 150]

total = 0

for price in prices:
    total += price

print("Total:", total)

Output: Total: 500

Example 3: Access Items with Their Index

names = ["Rahul", "Amit", "Priya"]

for index, name in enumerate(names):
    print(index, name)

Output:

0 Rahul
1 Amit
2 Priya

Use enumerate() when you need both the index and the item.

12. List Comprehension

List comprehension is a concise way to create a new list from an iterable.

Syntax

[expression for item in iterable]

Example 1: Create a List of Squares

squares = [number ** 2 for number in range(1, 6)]

print(squares)

Output: [1, 4, 9, 16, 25]

Example 2: Filter Even Numbers

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)

Output: [2, 4, 6]

Example 3: Convert Names to Uppercase

names = ["rahul", "amit", "priya"]

formatted_names = [name.upper() for name in names]

print(formatted_names)

Output: ['RAHUL', 'AMIT', 'PRIYA']

Use list comprehensions for clear, straightforward transformations and filters.

13. Nested Lists

A nested list is a list that contains other lists. It can represent tables, grids, and structured data.

Example

students = [
    ["Rahul", 85],
    ["Amit", 90],
    ["Priya", 92]
]

print(students[0])
print(students[1][0])
print(students[2][1])

Output:

['Rahul', 85]
Amit
92

Loop Through a Nested List

students = [
    ["Rahul", 85],
    ["Amit", 90],
    ["Priya", 92]
]

for student in students:
    print(f"Name: {student[0]}, Marks: {student[1]}")

Output:

Name: Rahul, Marks: 85
Name: Amit, Marks: 90
Name: Priya, Marks: 92

14. Copying Lists

Assigning one list variable to another does not create an independent copy. Both variables refer to the same list.

Example: Reference Assignment

first = [10, 20, 30]
second = first

second.append(40)

print(first)
print(second)

Output:

[10, 20, 30, 40]
[10, 20, 30, 40]

Creating a Shallow Copy

first = [10, 20, 30]
second = first.copy()

second.append(40)

print(first)
print(second)

Output:

[10, 20, 30]
[10, 20, 30, 40]

You can also create a shallow copy using first[:] or list(first). For nested lists, these methods do not copy the inner lists independently.

15. Python Tuples

A tuple is an ordered collection that cannot be modified after creation. Tuples are written using parentheses () in the common case.

Creating a Tuple

colors = ("Red", "Green", "Blue")

print(colors)

Output: ('Red', 'Green', 'Blue')

Accessing Tuple Items

colors = ("Red", "Green", "Blue")

print(colors[0])
print(colors[-1])

Output:

Red
Blue

Creating a Single-Item Tuple

A comma is required when creating a single-item tuple.

value = (10,)

print(value)
print(type(value))

Output:

(10,)
<class 'tuple'>

Without the comma, (10) is an integer expression, not a tuple.

16. Tuple Indexing and Slicing

Like lists, tuples support positive indexing, negative indexing, and slicing.

numbers = (10, 20, 30, 40, 50)

print(numbers[1])
print(numbers[-1])
print(numbers[1:4])
print(numbers[::-1])

Output:

20
50
(20, 30, 40)
(50, 40, 30, 20, 10)

Slicing a tuple returns a new tuple.

17. Tuple Immutability

Tuples do not allow individual items to be reassigned, added, or removed.

The following code raises a TypeError:

colors = ("Red", "Green", "Blue")

colors[0] = "Yellow"

If you need a modified tuple, create a new one.

colors = ("Red", "Green", "Blue")

colors = ("Yellow",) + colors[1:]

print(colors)

Output: ('Yellow', 'Green', 'Blue')

Important: A tuple can contain a mutable object, such as a list. The tuple's item reference cannot be replaced, but the contained list may still be modified.

18. Tuple Methods and Built-in Functions

Tuples have two commonly used methods:

  • count() — counts occurrences of a value.

  • index() — returns the index of the first matching value.

Example

numbers = (10, 20, 10, 30, 10)

print(numbers.count(10))
print(numbers.index(20))
print(len(numbers))
print(min(numbers))
print(max(numbers))
print(sum(numbers))

Output:

3
1
5
10
30
70

The built-in functions shown here work with this tuple because its values are numeric.

19. Tuple Packing and Unpacking

Tuple Packing

Packing means placing multiple values into a tuple.

student = "Rahul", 22, "Python"

print(student)

Output: ('Rahul', 22, 'Python')

Tuple Unpacking

Unpacking assigns tuple items to separate variables.

name, age, course = ("Rahul", 22, "Python")

print(name)
print(age)
print(course)

Output:

Rahul
22
Python

The number of variables should match the number of unpacked items, unless you use starred unpacking.

Extended Unpacking

numbers = (10, 20, 30, 40, 50)

first, *middle, last = numbers

print(first)
print(middle)
print(last)

Output:

10
[20, 30, 40]
50

The starred variable receives a list of the remaining values.

20. Converting Between Lists and Tuples

You can convert a tuple to a list and a list to a tuple.

Tuple to List

colors = ("Red", "Green", "Blue")

color_list = list(colors)
color_list.append("Yellow")

print(color_list)

Output: ['Red', 'Green', 'Blue', 'Yellow']

List to Tuple

numbers = [10, 20, 30]

number_tuple = tuple(numbers)

print(number_tuple)

Output: (10, 20, 30)

These conversions are useful when you need to modify data that is currently stored in a tuple or create a tuple from a collection.

21. Difference Between Lists and Tuples

Feature List Tuple
Syntax [ ] ( ) commonly
Ordered Yes Yes
Mutable Yes No
Allows duplicates Yes Yes
Indexing Supported Supported
Slicing Returns a list Returns a tuple
Common methods Many count(), index()
Best suited for Changeable collections Fixed collections

When to use a List: Use a list when items may need to be added, removed, sorted, or updated.

When to use a Tuple: Use a tuple when you want an ordered collection whose item references should not be reassigned.

22. Practical Project: Student Marks Manager

This project stores student names and marks, then displays each student's result and the class average.

students = [
    ("Rahul", 85),
    ("Amit", 90),
    ("Priya", 92)
]

total_marks = 0

print("------ STUDENT RESULTS ------")

for name, marks in students:
    total_marks += marks
    status = "Pass" if marks >= 40 else "Fail"

    print(f"Name: {name:<10} Marks: {marks:>3} Status: {status}")

average = total_marks / len(students)

print("-----------------------------")
print(f"Class Average: {average:.2f}")

Output:

------ STUDENT RESULTS ------
Name: Rahul      Marks:  85 Status: Pass
Name: Amit       Marks:  90 Status: Pass
Name: Priya      Marks:  92 Status: Pass
-----------------------------
Class Average: 89.00

This project uses a list to store multiple student records and tuples to represent each student's name and marks.

23. Practical Project: Shopping Cart

This project calculates the total price of items stored in a list of tuples.

cart = [
    ("Keyboard", 750.00, 2),
    ("Mouse", 400.00, 1),
    ("Monitor", 8500.00, 1)
]

grand_total = 0

print("---------- SHOPPING BILL ----------")

for product, price, quantity in cart:
    subtotal = price * quantity
    grand_total += subtotal

    print(f"{product:<12} {quantity:>2} x ₹{price:>8,.2f} = ₹{subtotal:,.2f}")

print("-----------------------------------")
print(f"Grand Total: ₹{grand_total:,.2f}")

Output:

---------- SHOPPING BILL ----------
Keyboard      2 x ₹  750.00 = ₹1,500.00
Mouse         1 x ₹  400.00 = ₹400.00
Monitor       1 x ₹8,500.00 = ₹8,500.00
-----------------------------------
Grand Total: ₹10,400.00

This example combines lists, tuples, loops, unpacking, arithmetic, and f-string formatting.

24. Common Mistakes

Mistake 1: Accessing an Invalid Index

numbers = [10, 20, 30]
print(numbers[5])

This raises an IndexError because index 5 does not exist.

Mistake 2: Confusing append() and extend()

numbers = [1, 2]
numbers.append([3, 4])

print(numbers)

Output: [1, 2, [3, 4]]

Use extend([3, 4]) when you want the result [1, 2, 3, 4].

Mistake 3: Assigning the Result of sort()

numbers = [30, 10, 20]
numbers = numbers.sort()

print(numbers)

Output: None

Correct approach:

numbers = [30, 10, 20]
numbers.sort()

print(numbers)

Output: [10, 20, 30]

Mistake 4: Creating a Single-Item Tuple Without a Comma

value = (10,)
print(type(value))

The comma makes it a tuple. (10) alone is an integer expression.

Mistake 5: Trying to Change a Tuple Item

Tuple items cannot be reassigned directly. Create a new tuple or convert it to a list if modification is required.

25. Practice Programs

Try completing these programs yourself:

  1. Create a list of five numbers and print each item.

  2. Find the largest and smallest numbers in a list.

  3. Calculate the sum and average of list values.

  4. Add an item using append().

  5. Insert an item using insert().

  6. Remove a selected item from a list.

  7. Sort numbers in ascending and descending order.

  8. Reverse a list using slicing.

  9. Count duplicate values using count().

  10. Create a list of squares using list comprehension.

  11. Extract even numbers from a list.

  12. Create a nested list of student names and marks.

  13. Copy a list and demonstrate that the copy is independent for a flat list.

  14. Create a tuple of five programming languages.

  15. Access tuple values using positive and negative indexing.

  16. Convert a tuple to a list and add an item.

  17. Unpack a tuple into variables.

  18. Count occurrences of a value in a tuple.

  19. Build a student marks report using a list of tuples.

  20. Build a shopping cart that calculates a grand total.

26. Quiz: Test Your Knowledge

Q1. What is a Python list?

Answer: An ordered, mutable collection that can contain duplicate values.

Q2. What is a Python tuple?

Answer: An ordered, immutable collection that can contain duplicate values.

Q3. Which brackets are commonly used for lists?

Answer: Square brackets [].

Q4. Which method adds one item to the end of a list?

Answer: append().

Q5. What is the difference between append() and extend()?

Answer: append() adds its argument as one item; extend() adds items from an iterable.

Q6. Are tuples mutable?

Answer: No, tuple item references cannot be reassigned.

Q7. What does list slicing return?

Answer: A new list.

Q8. What does sorted() return?

Answer: A new sorted list when applied to a list.

Q9. How do you create a one-item tuple?

Answer: Include a trailing comma, for example (10,).

Q10. What is tuple unpacking?

Answer: Assigning tuple items to separate variables.

27. Assignment

Build a Student and Shopping Data Manager with two sections.

Section A: Student Manager

  1. Store at least five students and their marks.

  2. Use tuples for individual student records.

  3. Display each student's name, marks, and pass/fail status.

  4. Calculate the highest mark and class average.

  5. Display students in descending order of marks.

Section B: Shopping Cart

  1. Store products, prices, and quantities in a list of tuples.

  2. Display each product's subtotal.

  3. Calculate the grand total.

  4. Add a new product to the cart.

  5. Display the updated bill using formatted output.

Use lists, tuples, loops, conditions, built-in functions, and f-strings throughout the assignment.

28. Summary

In this complete tutorial, you learned:

  • How to create lists and tuples.

  • Positive and negative indexing.

  • Slicing, updating, adding, and removing list items.

  • Important list methods such as append(), extend(), insert(), remove(), pop(), and sort().

  • Sorting, searching, copying, and looping through lists.

  • List comprehension and nested lists.

  • Tuple creation, indexing, slicing, and immutability.

  • Tuple methods, packing, unpacking, and conversions.

  • Differences between lists and tuples.

  • Practical student-report and shopping-cart projects.

  • Common mistakes, practice programs, quizzes, and assignments.

Conclusion: Lists and tuples are fundamental Python data structures. Lists are useful for collections that change over time, while tuples are suitable for ordered collections whose item references should remain fixed. Understanding both will help you build more organized and maintainable Python programs.

←
Post 10 of 20
→