5. Topic 5(COLON) Data Structures and Program Design

Lesson 5.1: Lists, Tuples And Iteration Over Collections

Official syllabus section covering Lesson 5.1: Lists, Tuples and Iteration over Collections within Topic 5: Data Structures and Program Design: Lists as ordered, mutable collections; creating, indexing, slicing and modifying them.; Common list operations and methods (append, insert, remove, sort) and iterating over a list..

Lesson 5.1: Lists, Tuples and Iteration over Collections

Introduction

In this lesson, students will explore the foundational concepts of data structures, focusing on lists and tuples, and how to effectively iterate over collections in programming. This lesson aims to:

  • Understand lists as ordered, mutable collections and learn how to create, index, slice, and modify them.
  • Explore common list operations and methods such as append, insert, remove, and sort, along with techniques for iterating over lists.
  • Define tuples as ordered, immutable collections, and understand when to use them effectively.
  • Make decisions about when to use lists versus tuples based on the mutability of the data.
  • Develop skills to create and manipulate lists, including adding, removing, and updating elements.

By the end of this lesson, students should feel comfortable working with these data structures, understanding their properties, and applying them in various situations within programming.

1. Understanding Lists

1.1 What is a List?

A list is an ordered collection of items, which can be changed (mutable) after its creation. Lists allow you to store multiples items in a single variable.

Characteristics of Lists:

  1. Ordered: The items in a list have a defined order, which means that the order in which you insert the items is preserved.
  2. Mutable: You can change the items in a list after it is created. This includes adding, removing, or changing items.
  3. Heterogeneous: Lists can contain items of different data types (e.g., integers, strings, and other lists).

1.2 Creating and Initializing Lists

Creating a list can be done easily using square brackets. Here's how to create a simple list:

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

students can also create an empty list and add items later:

my_empty_list = []

1.3 Indexing Lists

Lists use zero-based indexing, meaning the first item has an index of 0. Let’s see how to access list items with indexing:

print(my_list[0]) # Outputs: 1
print(my_list[2]) # Outputs: 3

1.4 Slicing Lists

Slicing allows you to access a range of items in a list. The syntax is: list[start:stop:step].

For example:

sliced_list = my_list[1:4]  # Outputs: [2, 3, 4]

1.5 Modifying Lists

You can modify lists in various ways:

  • Append: Add an element to the end of a list using append.
my_list.append(6)  # my_list is now [1, 2, 3, 4, 5, 6]
  • Insert: Insert an element at a specific index using insert.
my_list.insert(0, 0)  # Inserts 0 at the beginning
  • Remove: Remove an element from the list using remove.
my_list.remove(3)  # Removes the first occurrence of 3
  • Sort: Sort the elements of a list in ascending order using sort.
my_list.sort()  # my_list is now sorted

Worked Example: Modifying a List

Consider the list numbers = [10, 20, 30, 40]. Let’s go through some modifications:

  1. Append a value:
numbers.append(50)  # numbers becomes [10, 20, 30, 40, 50]
  1. Insert a value:
numbers.insert(2, 25)  # numbers becomes [10, 20, 25, 30, 40, 50]
  1. Remove a value:
numbers.remove(40)  # numbers becomes [10, 20, 25, 30, 50]
  1. Sort the list:
numbers.sort()  # numbers becomes [10, 20, 25, 30, 50]

2. Iterating Over Lists

2.1 Looping Through a List

Iteration allows you to access each element in a list. You can use a for loop to iterate through the elements:

for number in numbers:
    print(number)

This will output each number in the numbers list.

2.2 Using List Comprehensions

List comprehensions provide a concise way to create lists. The syntax is as follows:

new_list = [expression for item in iterable]

For example, if you want to create a new list with doubled values:

doubled_numbers = [number * 2 for number in numbers]  # Results in [20, 40, 50, 60, 100]

Worked Example: Iterating and Modifying a List

Let’s say we have the original list:

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

We can iterate through this list and modify it by appending a prefix:

for i in range(len(fruits)):
    fruits[i] = "Fresh " + fruits[i]  # Now fruits contains ["Fresh apple", "Fresh banana", "Fresh cherry"]

3. Understanding Tuples

3.1 What is a Tuple?

A tuple is similar to a list in that it is an ordered collection of items; however, tuples are immutable, meaning once they are created, their items cannot be modified.

Characteristics of Tuples:

  1. Ordered: Like lists, items in a tuple have a defined order.
  2. Immutable: Items cannot be changed, added, or removed.
  3. Heterogeneous: Can have items of different data types.

3.2 Creating Tuples

To create a tuple, use parentheses instead of square brackets:

tuple_example = (1, 2, 3)
empty_tuple = ()

3.3 Accessing Tuple Elements

Tuple indexing is the same as lists:

print(tuple_example[0])  # Outputs: 1

3.4 When to Use Tuples

Tuples should be used when you need a collection of items that should not change throughout the program. They can serve as fixed data, such as coordinate pairs or RGB color values.

Worked Example: Using a Tuple

Suppose we have coordinate points:

coordinates = (10, 20)

Here, coordinates is a tuple that holds fixed integer values representing points in a 2D space, and any attempt to alter it would raise an error.

4. Choosing Between Lists and Tuples

4.1 Key Differences

  • Mutability: Lists are mutable, while tuples are immutable.
  • Performance: Tuples can be slightly faster than lists when you need to store a collection of items that will not be changed.
  • Use Cases: Use lists when you need to modify data and tuples for fixed values.

4.2 Common Misconceptions

A common misconception is that tuples cannot be changed at all. While you cannot modify an element within a tuple, you can create a new tuple that includes different elements derived from the original one.

For instance:

new_coordinates = (coordinates[0], 30)  # Changes the y-coordinate while keeping x

Conclusion

In this lesson, students has explored the fundamental concepts regarding lists and tuples, their properties, and their applications. Lists serve as mutable collections allowing for dynamic data handling, while tuples provide stability and consistency when dealing with fixed data sets. Practicing operations on these data structures will be crucial for developing effective programs.

Study Notes

  • Lists are ordered and mutable collections of items.
  • Use square brackets for lists and parentheses for tuples.
  • List methods: append, insert, remove, sort.
  • Tuples are immutable and should be used for fixed data.
  • Choose lists for changeable data and tuples for unchangeable data.
  • Use for loops and list comprehensions for iterating over collections.

Practice Quiz

5 questions to test your understanding

Lesson 5.1: Lists, Tuples And Iteration Over Collections — Information Technology | A-Warded