0% found this document useful (0 votes)
11 views47 pages

Week 5

The document provides an overview of lists and tuples in Python, highlighting their importance as data structures for storing and managing multiple types of data. It explains the differences between lists (mutable) and tuples (immutable), as well as how to create, access, modify, and iterate through these data structures. Additionally, it includes exercises to reinforce understanding of list operations and functions.

Uploaded by

hmlong03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views47 pages

Week 5

The document provides an overview of lists and tuples in Python, highlighting their importance as data structures for storing and managing multiple types of data. It explains the differences between lists (mutable) and tuples (immutable), as well as how to create, access, modify, and iterate through these data structures. Additionally, it includes exercises to reinforce understanding of list operations and functions.

Uploaded by

hmlong03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Week 5:

Lists and
Tuples

LISTS AND TUPLES 1


Introduction to Data Structures
Let’s explore an example.
Example Scenario:
 Imagine you need to store information for a single student:

• Name (String)

• Age (Integer)

• Grade (Float)

LISTS AND TUPLES 2


Limitations of Primitive Data Type
 What if we need to store and manage multiple types of data for many entities (like students in
a class)?
 Storing information for multiple students would require multiple variables for each student.
Example:

LISTS AND TUPLES 3


Why Do We Need Data Structures?
 We need a more scalable way to store data for multiple students.

 What if we also need to store more complex details? (e.g., Address, Phone number, Courses)

 Primitive data types (e.g., integers, floats, strings) are useful for simple data.

 Solution: Data structures can hold multiple types of data and scale with size.

LISTS AND TUPLES 4


Primitive Data Types
 Primitive data types, such as integers, floats, and characters, can hold only single values.
 Primitive data types have fixed sizes in memory, which can be limiting for managing large or
dynamically changing datasets.
 When working with primitive data types, you may need to write more complex and less
efficient algorithms to manipulate and process data.
 While primitive types are essential for low-level operations, they may not be sufficient for
modeling and solving complex real-world problems.
 Primitive types may require you to duplicate code when handling similar data in different parts
of your program.

LISTS AND TUPLES 5


Data Structures
• While primitive data types are essential building blocks in programming, data structures expand
the capabilities of your programs.
 Data structures are fundamental concepts in computer science and programming that define
how data is organized, stored, and manipulated in a computer program.
 Data structures are designed to optimize storage and retrieval. For example, lists, arrays, and
dictionaries in Python can dynamically allocate memory, making them more efficient for
handling changing data sizes.
 They play a crucial role in solving various computational problems efficiently. Using
appropriate data structures can lead to simpler and more efficient algorithms.
 Data structures allow you to organize and store multiple values, possibly of different types, in a
structured way.

LISTS AND TUPLES 6


Data Structures
 Python has several built-in data structures, and you can also create your own custom data
structures.

 Here's an overview of some commonly used data structures in Python:


• Lists
• Tuples
• Dictionaries
• Sets

LISTS AND TUPLES 7


Lists and Tuples
 Lists and tuples are examples of sequences in Python.

 Lists and tuples are used to store a collection of items.

Lists:
• Lists are ordered collections of items, and they are one of the most versatile data structures in Python.
• Lists can hold items of different data types and allow for dynamic resizing.
• You can access elements by their index, append, insert, remove, and perform various other operations
on lists.

Tuples:
• Tuples are similar to lists but are immutable, meaning their items cannot be changed after creation.
• They are often used to represent collections of related data.

LISTS AND TUPLES 8


Creating Lists
 To create a list, use square brackets [ ] and separate the items with commas.

• You can create an empty list by using empty square brackets.

• To create a list with items, enclose the items in square brackets.

LISTS AND TUPLES 9


Creating Lists
Creating a list with mixed data types:

 Lists in Python can hold elements of different data types.

Here, the list mixed_list contains an integer, a string, a float, and a boolean.

LISTS AND TUPLES 10


Accessing List Elements (Single Element )
 To access a single element in a list, use square brackets [ ] with the index of the element you
want to retrieve.

 The index is zero-based, meaning the first element has an index of 0, the second element has
an index of 1, and so on.

LISTS AND TUPLES 11


Accessing List Elements (Single Element )
Accessing Elements from the End:
 You can also use negative indices to access elements from the end of the list. -1 refers to the
last element, -2 to the second-to-last, and so on.

LISTS AND TUPLES 12


Accessing Multiple Elements (Slicing):
 You can access a range of elements within a list using slicing.

 Slicing is done by specifying a start index (inclusive) and an end index (exclusive) separated by
a colon : inside the square brackets.

 If you omit the start or end index, Python assumes that you want to start from the beginning
or go to the end of the list, respectively.

LISTS AND TUPLES 13


Modifying Lists
 In Python, you can modify the content of a list as needed. Modifying a list means changing the
values of existing elements, adding new elements, or removing existing elements.

 Lists are mutable, which means you can modify them in place.

 Lists are flexible data structures, making them suitable for various programming tasks.

LISTS AND TUPLES 14


Changing the Value of an Element
 To change the value of an element at a specific index in a list, simply assign a new value to that
index using the assignment operator =

LISTS AND TUPLES 15


Built-in List Methods
 There are many built-in list methods in Python, including append(), insert(), and remove():

Adding Elements to a List:


• You can add elements to the end of a list using the append() method.
• This method adds a single element to the list.

LISTS AND TUPLES 16


Adding Multiple Elements to a List:
 To add multiple elements to a list, you can use the extend() method or the + operator for
concatenation.

LISTS AND TUPLES 17


Inserting Elements at a Specific Index
 You can insert an element at a specific index using the insert() method.
 This method takes two arguments: the index at which to insert the element and the element
itself.

LISTS AND TUPLES 18


Removing Elements from a List
 You can remove elements from a list using several methods:
 To remove an element by its value, you can use the remove() method.
 It removes the first occurrence of the given value.

LISTS AND TUPLES 19


Removing Elements from a List
 To remove an element by its index, you can use the pop() method.
 It removes the element at the specified index and returns its value.
 If you don't specify an index, it removes and returns the last element by default.

LISTS AND TUPLES 20


Removing Elements from a List
 You can also use the del statement to remove elements by index or slice.

LISTS AND TUPLES 21


Removing Elements from a List
Clearing a List:
 To remove all elements from a list and make it empty, you can use the clear() method or assign
an empty list to it.

LISTS AND TUPLES 22


Creating a List with the list() function
 You can use the list() function to create a list from an iterable object, such as a string, tuple, or
another list.

LISTS AND TUPLES 23


Creating a List with List Comprehension
 List comprehensions provide a concise way to create lists based on existing lists or other
iterable objects.

LISTS AND TUPLES 24


Iterating Over Lists
 Once we store multiple items in a list, we often need to access or manipulate each item.

 Python offers different ways to iterate over a list, meaning we can go through each element in
the list one by one.

• Method 1: Using a for Loop


• Method 2: Using range() and len()
• Method 3: Using enumerate()

LISTS AND TUPLES 25


Method 1: Using a for Loop
Example of iterating through a list using a for loop:

 The loop goes through each element (student) in the students list.
 This method is simple and commonly used.

LISTS AND TUPLES 26


Method 2: Using range() and len()
If you need both the index and value of the list elements:

 range(len(students)) generates indices for the list.


 This allows access to both the index (i) and the element (students[i]).

LISTS AND TUPLES 27


Method 3: Using enumerate()
The enumerate() function makes accessing both index and value easier:

 enumerate() returns both the index and the element in each iteration.
 Cleaner than using range() and len().

LISTS AND TUPLES 28


Nested Lists
 Lists can also contain other lists, creating nested structures.
 A nested list is essentially a list that contains other lists as its elements.
 In this example, nested_list contains sublists as its elements.

LISTS AND TUPLES 29


Accessing Elements of a Nested List
 Accessing elements of a nested list in Python involves using multiple indices to navigate
through the layers of nesting.

 To access elements within a nested list, you need to provide the index for each level of nesting.

 You start by accessing a sublist using an index, and then you access elements within that
sublist using another index.

 This process can be repeated to access elements at deeper levels of nesting within the list.

LISTS AND TUPLES 30


Accessing Elements at the Outer Level
 You can access the sublists within the nested list using single indices.
For example, to access the second sublist [4, 5, 6], use the index 1:

Now, the sublist contains [4, 5, 6].

LISTS AND TUPLES 31


Accessing Elements within a sublist
 Once you have accessed a sublist, you can use another set of indices to access elements within
that sublist.
For example, to access the element 5 within the sublist [4, 5, 6], use the index 1 again:

LISTS AND TUPLES 32


Accessing Elements directly
 You can also combine these steps and access elements within a nested list directly by
specifying both sets of indices.
This accesses the element 5 in a single step:

LISTS AND TUPLES 33


Iterating through a nested list
 To traverse all elements in a nested list, you can use nested loops.
For example, to print all elements in nested_list:

 This code will iterate through each sublist in the outer list and then iterate through each
element within the sublists, printing all elements.

LISTS AND TUPLES 34


Iterating through a nested list
Here's how the code works:
1. The outer loop for sublist in nested_list: iterates through each sublist in nested_list.
• In the first iteration, sublist will be [1, 2, 3].
• In the second iteration, sublist will be [4, 5, 6].
• In the third iteration, sublist will be [7, 8, 9].

2. The inner loop for element in sublist: iterates through each element within the current
sublist.
• In the first iteration of the inner loop, element will be 1, then 2, and finally 3 as it goes through [1, 2, 3].
• In the second iteration of the outer loop, element will be 4, then 5, and finally 6 as it goes through [4, 5, 6].
• In the third iteration of the outer loop, element will be 7, then 8, and finally 9 as it goes through [7, 8, 9].

LISTS AND TUPLES 35


Tuples VS Lists
 A tuple in Python is similar to a list in that it is an ordered collection of elements. However,
there are several key differences between tuples and lists:
Mutability:
List: Lists are mutable, which means you can change, add, or remove elements after the list is
created. You can use methods like append(), insert(), and remove() to modify lists.
Tuple: Tuples are immutable, meaning that once you create a tuple, you cannot change its
elements. Once a tuple is defined, you cannot add, remove, or modify its elements.
This immutability provides data integrity and makes tuples suitable for situations where you
want to ensure the data remains unchanged.

LISTS AND TUPLES 36


Tuples VS Lists
Syntax:
List: Lists are defined using square brackets [ ]. Elements in a list are separated by commas.
Tuple: Tuples are defined using parentheses ( ). Elements in a tuple are also separated by
commas.

LISTS AND TUPLES 37


Accessing Tuple Elements and Iterating
 Tuple elements can be accessed using indexing, just like lists:

 Tuples can be iterated over just like lists, but they are immutable.

LISTS AND TUPLES 38


Iterating through a Nested Tuple
 In this example, nested_tuple is containing three tuples, each with three elements.
 We use a nested for loop to iterate through the outer tuple and the inner tuples.

LISTS AND TUPLES 39


Iterating through a Nested Tuple
Here's how the code works:
1. The outer loop for subtuple in nested_tuple: iterates through each subtuple in nested_tuple.
• In the first iteration, subtuple will be (1, 2, 3).
• In the second iteration, subtuple will be (4, 5, 6).
• In the third iteration, subtuple will be (7, 8, 9).

2. The inner loop for element in subtuple: iterates through each element within the current
inner tuple.
• In the first iteration of the inner loop, element will be 1, then 2, and finally 3 as it goes through (1, 2, 3).
• In the second iteration of the outer loop, element will be 4, then 5, and finally 6 as it goes through (4, 5, 6).
• In the third iteration of the outer loop, element will be 7, then 8, and finally 9 as it goes through (7, 8, 9).

LISTS AND TUPLES 40


Exercises
 Write a function that takes a list of integers as an argument and returns the sum of the even
integers in the list.

# Example:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Creating a list of integers
result = list_sum_even(my_list) # Calling the function and passing the list of integers
print(f"Sum of even integers: {result}") # Output: Sum of even integers: 30

LISTS AND TUPLES 41


Exercises
 Write a function that takes a list of strings as an argument and returns a new list with the
length of each string.

# Example:
my_strings = ["fiat", "volvo", "hyundai", "mercedesbenz", "nissan"] # Creating a list of strings
lengths = string_lengths(my_strings) # Calling the function and passing the list of strings
print(f"Lengths of strings: {lengths}") # Output: Lengths of strings: [4, 5, 7, 12, 6]

LISTS AND TUPLES 42


Exercises
 Write a function that takes a list of numbers as input and returns a new list where the odd
numbers are doubled, and the even numbers remain unchanged.

# Example:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Creating a list of integers
result = double_odd_numbers(my_list) # Calling the function and passing the list of integers
print(result) # Output: [2, 2, 6, 4, 10, 6, 14, 8, 18]

LISTS AND TUPLES 43


Exercises
 Write a function that finds and returns the largest element in a list of numbers.

# Example:
my_list = [12, 45, 78, 23, 56, 89, 34] # Creating a list of integers
largest_number = find_largest_element(my_list) # Calling the function and passing the list of
integers
print(f"The largest number is: {largest_number}") # Output: The largest number is: 89

LISTS AND TUPLES 44


Exercises
 Write a function that takes a tuple and a value as input and returns True if the value is found in
the tuple, otherwise returns False.

# Example:
my_tuple = (10, 20, 30, 40, 50) # Creating a tuple of integers
result = tuple_contains(my_tuple, 30) # Calling the function and passing the tuple and a value
print(result) # Output: True

LISTS AND TUPLES 45


Exercises
 Write a function that takes a nested list of integers and returns a new list with the sum of each
sublist. Provide two different implementations of the function: one using the sum() function and
the other using a nested loop.

# Example:
nested_lists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Creating a nested list of integers
result = sum_nested_lists(nested_lists) # Calling the function and passing the nested list
print(f"Sums of sublists: {result}") # Output: Sums of sublists: [6, 9, 30]

LISTS AND TUPLES 46


Exercises
 Write a function that takes a nested list of integers and returns the sum of all elements.

# Example:
nested_lists = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Creating a nested list of integers
result = sum_all_elements(nested_lists) # Calling the function and passing the nested list
print(f"Sum of all elements: {result}") # Output: Sum of all elements: 45

LISTS AND TUPLES 47

You might also like