Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

4/25/24, 10:30 PM Notebook.

ipynb - Colab

keyboard_arrow_down Lists
Lists are an essential and fundamental data structure in programming. They serve as ordered
collections that enable you to store and organize multiple items in a structured manner.

keyboard_arrow_down Motivation
Welcome to your journey of learning about lists in programming! Let's explore the key reasons
why learning about lists is valuable:

Data Storage and Organization: Lists are like special containers that can hold lots of things
together. They help you store and organize different pieces of data in one place. It's like
having a box where you can keep your favorite snacks. Lists make it easier to keep track of
and work with collections of data.

Iterating and Manipulating Data: Lists allow you to do cool things with your data. You can
go through each item in the list and do something with it. You can change, add, or take
away things from the list, just like adding more snacks to your box. Lists give you the
power to work with data in many different ways.

Lists Creation
In Python, lists are created by enclosing elements within square brackets ( [] ), and each element
is separated by a comma. Lists can store elements of different types, including numbers, strings,
or even other lists. Here are a few examples of lists:

A list of integers: [1, 2, 3, 4, 5]


A list of strings: ["apple", "banana", "cherry"]
A list of mixed data types: [10, "hello", 3.14]

To create an empty list, you can use empty square brackets ( [] ), indicating that the list contains
no elements.

empty_list = []

keyboard_arrow_down List characteristics


1. Ordered: Lists maintain the order of elements as they are added. The position of an
element in a list is determined by its index.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 1/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

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


print(fruits[0]) # Output: "apple"

apple

2. Mutable: Lists are mutable, meaning you can modify, add, or remove elements after the
list is created. This allows for dynamic changes to the list's content.

numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4, 5]

[1, 2, 10, 4, 5]

3. Heterogeneous Elements: Lists can contain elements of different data types. You can
have a mix of integers, strings, or even other lists within a single list.

mixed_list = [1, "hello", [2, 4, 6]]

4. Variable Length: Lists can grow or shrink dynamically as elements are added or
removed. They do not have a fixed size, allowing for flexibility in managing varying amounts
of data. We will see how to do that later in this lesson.

Double-click (or enter) to edit

keyboard_arrow_down Indexing and Slicing


Indexing and slicing are fundamental operations that allow you to access specific elements or a
range of elements within a list.

Indexing

In the context of lists, an index refers to the position or location of an element


within the list. Each element in a list is assigned a unique index value that allows
you to access and manipulate that element. Indexing involves accessing individual
elements of a list by their index values.

Indexing starts at 0 : In most programming languages, including Python, indexing starts


from 0 . The first element in a list has an index of 0 , the second element has an index of 1 ,
and so on. The last element of a list can be accessed using the index len(list_name) - 1 .

Negative indexing: Lists also support negative indexing, where the index -1 refers to the
last element, -2 refers to the second-to-last element, and so on. Negative indices count

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 2/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

from the end of the list towards the beginning.

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


print(fruits[0]) # Output: "apple"
print(fruits[1]) # Output: "banana"
print(fruits[-1]) # Output: "cherry"
print(fruits[-2]) # Output: "banana"

apple
banana
cherry
banana

Out-of-range indices: If you try to access an index that is outside the valid range of indices
for a list, you'll get an IndexError . It's important to ensure that the index is within the range
of the list to avoid such errors.

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


print(fruits[3]) # IndexError: list index out of range

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 6 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> print(fruits[3])

In this example, the list fruits has three elements with indices 0 , 1 , and 2 . However, when we
try to access the element at index 3 using fruits[3] , it goes beyond the valid range of indices.
As a result, Python raises an IndexError indicating that the list index is out of range.

To avoid this error, you need to ensure that the index you're trying to access is within the valid
range of indices for the list. In this case, valid indices for fruits range from 0 to 2 (inclusive), so
accessing fruits[2] will give you the last element of the list without causing an IndexError .

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 3/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

keyboard_arrow_down Slicing
Slicing allows you to extract a portion of a list by specifying a range of indices. It creates a new
list containing the selected elements. The syntax for slicing is start_index : stop_index .

The start_index parameter in slicing denotes the index at which the slicing operation begins.
The element at the start_index is included in the slice. The stop_index parameter in slicing
denotes the index at which the slicing operation ends. The element at the stop_index is not
included in the slice.

numbers = [1, 2, 3, 4, 5]
sliced_list = numbers[1:4]
print(sliced_list) # Output: [2, 3, 4]

[2, 3, 4]

In the example above, numbers[1:4] returns a new list containing elements from index 1
(inclusive) to index 4 (exclusive), which are the elements [2, 3, 4] in the original list.

Omitting indices: When you omit the start_index in a slice, it defaults to 0 , and when you
omit the stop_index , it defaults to the length of the list.

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

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

In the example above, numbers[:3] returns a new list containing the elements from the start of
the list up to index 3 . numbers[2:] returns a new list containing elements from index 2 to the
end of the list. numbers[:] returns a copy of the entire list.

keyboard_arrow_down Nested Lists


In Python, a nested list is a list that contains other lists as elements. This concept allows you to
create complex data structures that can store multiple levels of information. Each nested list can
have its own elements, including other nested lists. This hierarchical structure enables you to
represent data in a more organized and structured manner.

Creating Nested Lists

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 4/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

To create a nested list, you can simply include lists as elements within another list. Here's an
example:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In the above example, nested_list contains three inner lists, each representing a row of values.
The outer list encapsulates these inner lists, forming a nested structure.

keyboard_arrow_down Accessing Elements in Nested Lists


To access elements in a nested list, you use multiple index positions. The first index represents
the outer list's position, and the second index represents the position within the inner list. Here's
an example:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


print(nested_list[0]) # Output: [1, 2, 3]
print(nested_list[1][1]) # Output: 5

[1, 2, 3]
5

In the above example, nested_list[0] retrieves the first inner list [1, 2, 3] . To access the
value 5 within the second inner list, you use nested_list[1][1] .

keyboard_arrow_down Modifying Nested Lists


You can modify elements within a nested list using assignment. Access the desired element
using indexing and assign a new value to it. Here's an example:

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


nested_list[1][0] = 10
print(nested_list) # Output: [[1, 2, 3], [10, 5, 6], [7, 8, 9]]

[[1, 2, 3], [10, 5, 6], [7, 8, 9]]

In the above example, nested_list[1][0] represents the element 4 within the second inner list.
By assigning it a new value of 10 , we modify the nested list accordingly.

keyboard_arrow_down List Operations


List operations refer to various actions or manipulations that can be performed on lists. Here are
some common list operations:

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 5/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

Concatenation ( + operator):
Lists can be concatenated using the + operator. It combines two or more lists into a single list,
preserving the order of elements.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated = list1 + list2
print(concatenated) # Output: [1, 2, 3, 4, 5, 6]

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

In this example, the + operator concatenates list1 and list2 , resulting in a new list named
concatenated .

keyboard_arrow_down Repetition ( * operator):

Lists can be repeated or multiplied using the * operator. It creates a new list by repeating the
elements of the original list a specified number of times.

numbers = [1, 2, 3]
repeated = numbers * 3
print(repeated) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

[1, 2, 3, 1, 2, 3, 1, 2, 3]

In this example, the * operator repeats the elements of the numbers list three times, creating a
new list named repeated .

keyboard_arrow_down Membership Testing ( in and not in operators):

You can test whether an element is present in a list using the in and not in operators. They
return a Boolean value ( True or False ) based on the presence or absence of the element in the
list.

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


print("banana" in fruits) # Output: True
print("orange" not in fruits) # Output: True

True
True

In this example, the in operator checks if "banana" is present in the fruits list, returning True .
The not in operator checks if "orange" is not present in the fruits list, returning True .

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 6/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

keyboard_arrow_down List Manipulations and Methods


Lists support various operations to interact with their elements. Understanding these operations
is essential for working effectively with lists. Here are some of the basic operations:

Accessing Elements
You can access individual elements of a list using their index values. Indices start from 0 for the
first element and can be negative to access elements from the end of the list.

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


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

apple
cherry

keyboard_arrow_down Modifying Elements


Lists are mutable, so you can modify the value of an element by assigning a new value to its
index.

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


numbers[2] = 35
print(numbers) # Output: [10, 20, 35, 40, 50]

[10, 20, 35, 40, 50]

keyboard_arrow_down Adding Elements


Adding elements to a list is a common operation when working with lists. There are several
methods available to add elements to a list.

append() method

The append() method is used to add an element to the end of a list. It takes a single argument,
which is the value to be added.

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


fruits.append("orange")
print(fruits) # Output: ["apple", "banana", "cherry", "orange"]

['apple', 'banana', 'cherry', 'orange']

keyboard_arrow_down insert() method

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 7/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

The insert() method allows you to add an element at a specific index within a list. It takes two
arguments: the index at which to insert the element and the value to be inserted.

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


fruits.insert(1, "orange")
print(fruits) # Output: ["apple", "orange", "banana", "cherry"]

['apple', 'orange', 'banana', 'cherry']

In this example, the insert() method is used to add the value "orange" at index 1 in the
fruits list. The existing elements are shifted to accommodate the new element.

keyboard_arrow_down extend() method

The extend() method allows you to add multiple elements from another list to the end of the
current list. It takes an iterable as an argument, such as another list or a string. Don't worry about
iterables for now as we will cover them in a later lecture, but for now just remember it is an
object that represents a collection of elements that can be accessed one by one.

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


more_fruits = ["orange", "mango"]
fruits.extend(more_fruits)
print(fruits) # Output: ["apple", "banana", "cherry", "orange", "mango"]

['apple', 'banana', 'cherry', 'orange', 'mango']

In this example, the extend() method is used to add the elements from the more_fruits list to
the fruits list. The resulting list contains all the elements from both lists.

keyboard_arrow_down Removing Elements


Lists provide several methods to remove elements. The remove() method removes the first
occurrence of a specified value from the list. It searches for the value and removes it if found. If
the value is not present in the list, a ValueError is raised.

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


fruits.remove("banana")
print(fruits) # Output: ["apple", "cherry"]

['apple', 'cherry']

Here's an example that demonstrates the usage of the remove() method and the ValueError
that is raised when the specified value is not found in the list:

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 8/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

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


fruits.remove("grape") # ValueError: list.remove(x): x not in list

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 24 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> fruits.remove("grape")

In this example, we have a list called fruits containing three elements: "apple" , "banana" , and
"cherry" . When we try to remove the value "grape" using the remove() method, a ValueError
is raised. This error occurs because the value "grape" is not present in the list. The remove()
method expects the value to exist in the list and removes only the first occurrence of that value.

The pop() method removes an element at a given index from the list and returns its value. If no
index is specified, it removes and returns the last element. This method allows you to remove
elements from the list while also capturing their values for further processing.

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


removed_number = numbers.pop(2)
print(removed_number) # Output: 30
print(numbers) # Output: [10, 20, 40, 50]

30
[10, 20, 40, 50]

It's important to note that if you try to pop() an index that is out of range, an IndexError will be
raised. Make sure to provide a valid index within the range of the list to avoid this error.

keyboard_arrow_down Sorting a List


Sorting a list involves arranging its elements in a specific order. Lists in Python provide the
sort() method, which allows you to sort the elements in ascending order by default. You can
also specify the reverse=True argument to sort the list in descending order.

numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 8, 9]

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


fruits.sort(reverse=True)
print(fruits) # Output: ["cherry", "banana", "apple"]

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.i… 9/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

[1, 2, 5, 8, 9]
['cherry', 'banana', 'apple']

In this example, the sort() method is used to sort the numbers list in ascending order and the
fruits list in descending order.

keyboard_arrow_down Reversing a List


Reversing a list involves changing the order of its elements. The reverse() method is available
for lists and allows you to reverse the order of elements in-place.

numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 2, 1]

[5, 4, 3, 2, 1]

keyboard_arrow_down Finding the Minimum and Maximum


To find the minimum and maximum values in a list, you can use the min() and max() functions,
respectively. These functions return the smallest and largest elements in the list.

numbers = [5, 2, 8, 1, 9]
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 9

1
9

keyboard_arrow_down Finding the length of a List


The len() function in Python allows you to determine the length or number of elements in a list.
It returns an integer representing the count of elements in the list.

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


length = len(fruits)
print(length) # Output: 3

keyboard_arrow_down Finding the index of an element using index()

The index() method allows you to find the index of a specific element within a list. It returns the
index of the first occurrence of the element in the list.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook… 10/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

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


index = fruits.index("banana")
print(index) # Output: 1

keyboard_arrow_down Joining List elements


The join() method allows you to concatenate the elements of a list into a single string. It takes
a string as an argument and joins the elements of the list using that string as a separator.

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


joined_string = ", ".join(fruits)
print(joined_string) # Output: "apple, banana, cherry"

apple, banana, cherry

keyboard_arrow_down Common List Errors and Troubleshooting


When working with lists in Python, you may encounter certain errors or issues. Understanding
common list errors and knowing how to troubleshoot them can help you write more robust code.
Here are a few common list errors and ways to address them:

IndexError

An IndexError occurs when you try to access an index that is outside the valid range of indices
for a list. This typically happens when the index is negative or greater than or equal to the length
of the list.

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


print(fruits[3]) # IndexError: list index out of range

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 60 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> print(fruits[3])

To troubleshoot an IndexError , ensure that the index you're trying to access is within the valid
range of indices for the list. Remember that list indices start from 0 and go up to len(list) -
1.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook.… 11/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

keyboard_arrow_down ValueError

A ValueError may occur when using methods like remove() or index() if the specified value is
not found in the list.

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


fruits.remove("orange") # ValueError: list.remove(x): x not in list

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 62 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> fruits.remove("orange")

To handle a ValueError , you should check if the value exists in the list before performing the
operation.

keyboard_arrow_down AttributeError

An AttributeError can occur when using incorrect or unsupported list operations or methods.
For example, attempting to sort a list that contains elements of different data types can result in
an AttributeError .

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


fruits.sort() # AttributeError: 'int' object has no attribute 'lower'

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 64 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry", 5]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> fruits.sort()

To resolve an AttributeError , ensure that you're using the appropriate methods and operations
supported by lists. Check the documentation or the specific error message to identify the cause
of the error.

Troubleshooting Tips

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook… 12/13


4/25/24, 10:30 PM Notebook.ipynb - Colab

Double-check your indices: Ensure that the indices you are using to access or modify list
elements are correct and within the valid range
Verify the presence of values: Before using methods like remove() or index() , confirm
that the value exists in the list to avoid ValueError
Check data types: If you encounter an AttributeError or unexpected behavior, review the
data types in your list and ensure they are compatible with the operations you're
performing
Print and debug: If you're unsure about the state of your list, print intermediate results or
use debugging techniques to identify any issues

By understanding these common list errors and following troubleshooting strategies, you can
handle and resolve issues that may arise while working with lists in Python.

Key Takeaways

Lists in Python are versatile data structures that allow you to store and manipulate
collections of items
Lists are declared using square brackets ( [] ), and they can contain elements of different
data types
Important list operations include concatenation ( + ), repetition ( * ), indexing ( [] ), slicing
( [:] ), length determination ( len() ), sorting ( sort() ), reversing ( reverse() ), finding the
minimum ( min() ) and maximum ( max() ) values, and joining elements into a string
( join() )
When working with lists, be mindful of common errors such as IndexError (accessing
indices out of range), ValueError (searching or removing non-existent values), and
AttributeError (using unsupported operations or methods)
Troubleshooting techniques for list errors include checking indices, verifying value
presence, reviewing data types, and utilizing print statements and debugging tools

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/8. Lists/Notebook… 13/13

You might also like