Lists and Tuples

Lists and Tuples

Lists

Creating Lists

# Empty list
numbers = []

With values

fruits = ["apple", "banana", "cherry"] mixed = [1, "hello", 3.14, True]

Accessing Elements

fruits = ["apple", "banana", "cherry"]

print(fruits[0]) # apple print(fruits[-1]) # cherry

Modifying Lists

fruits = ["apple", "banana"]

fruits.append("cherry") # Add to end fruits.insert(1, "orange") # Insert at index fruits.remove("apple") # Remove by value popped = fruits.pop() # Remove and return last

List Slicing

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

print(numbers[1:4]) # [1, 2, 3] print(numbers[:3]) # [0, 1, 2] print(numbers[3:]) # [3, 4, 5] print(numbers[::2]) # [0, 2, 4]

List Methods

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

print(len(numbers)) # 5 print(sorted(numbers)) # [1, 1, 3, 4, 5] print(numbers.count(1)) # 2 print(numbers.index(4)) # 2

Tuples

Creating Tuples

# Empty tuple
point = ()

Single element (needs comma)

single = (5,)

Multiple elements

coordinates = (10, 20, 30)

Tuple Immutability

# This will cause an error!
point = (10, 20)
point[0] = 15  # TypeError!

Tuple Packing/Unpacking

# Packing
person = ("John", 30, "London")

Unpacking

name, age, city = person print(name) # John print(age) # 30

Summary

  • Lists: mutable, dynamic arrays
  • Tuples: immutable, fixed collections
  • Both support indexing and slicing

Next Lesson

In the next lesson, you'll learn about dictionaries and sets.

Quiz - Quiz - Lists and Tuples

1. What is the main difference between lists and tuples?

2. How do you add an element to the end of a list?

3. What does tuple unpacking mean?

For and While Loops