Lists and Tuples

Lists and Tuples in Python

Introduction

Lists and tuples are fundamental sequence data types in Python. They allow you to store collections of items in a specific order.

Lists

Lists are mutable sequences that can store any type of Python object.

python
1
# Creating a list
2
fruits = ['apple', 'banana', 'orange']
3
4
# Accessing elements
5
print(fruits[0]) # Output: apple
6
7
# Modifying lists
8
fruits.append('grape')
9
fruits[1] = 'pear'
Loading tool...

Try it yourself

fruits = ['apple', 'banana', 'orange'] print("Original list:", fruits)

Add a new fruit

fruits.append('grape') print("After append:", fruits)

Modify an element

fruits[1] = 'pear' print("After modification:", fruits) [/tool]

Tuples

Tuples are immutable sequences, meaning they cannot be modified after creation.

python
1
# Creating a tuple
2
coordinates = (10, 20)
3
4
# Accessing elements
5
print(coordinates[0]) # Output: 10
Loading tool...

Try working with tuples

coordinates = (10, 20) print("Coordinates:", coordinates) print("X coordinate:", coordinates[0]) print("Y coordinate:", coordinates[1]) [/tool]

Key Differences

  1. Mutability:

    • Lists are mutable (can be modified)
    • Tuples are immutable (cannot be modified)
  2. Syntax:

    • Lists use square brackets []
    • Tuples use parentheses ()
  3. Common use cases:

    • Lists: Collection of items that might change
    • Tuples: Collection of related items that shouldn't change

Practice Exercise

Loading tool...

Create and manipulate lists and tuples

1. Create a list of numbers

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

2. Create a tuple of colors

colors = ('red', 'green', 'blue')

Print both collections

print("Numbers (list):", numbers) print("Colors (tuple):", colors)

Try to modify the list (will work)

numbers.append(6) print("Modified numbers:", numbers)

Try to modify the tuple (will raise an error)

try: colors[0] = 'yellow' except TypeError as e: print("Error:", e) [/tool]