0% found this document useful (0 votes)
7 views11 pages

Working With Lists - Ipynb - Colab

This document serves as a guide for working with lists in Python, covering essential skills such as creating, accessing, modifying, and organizing lists. It introduces key concepts like indexing, slicing, and various methods for manipulating list elements, including append(), insert(), pop(), and remove(). Additionally, it highlights the differences between lists and tuples, emphasizing the mutable nature of lists versus the immutability of tuples.
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)
7 views11 pages

Working With Lists - Ipynb - Colab

This document serves as a guide for working with lists in Python, covering essential skills such as creating, accessing, modifying, and organizing lists. It introduces key concepts like indexing, slicing, and various methods for manipulating list elements, including append(), insert(), pop(), and remove(). Additionally, it highlights the differences between lists and tuples, emphasizing the mutable nature of lists versus the immutability of tuples.
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/ 11

2/4/25, 3:37 PM working_with_lists.

ipynb - Colab

To start working on this notebook, or any other notebook that we will use in this course, we will
need to save our own copy of it. We can do this by clicking File > Save a Copy in Drive. We will
then be able to make edits to our own copy of this notebook.

keyboard_arrow_down Working With Lists


keyboard_arrow_down Introduction
Embarking on our Python programming journey, our primary focus today is on mastering the
essential skills surrounding lists. We, as programmers, utilize lists as dynamic containers,
offering a versatile way to efficiently organize and manipulate data. Whether managing
numbers, names, or diverse data types, our ability to create, access, and modify lists is pivotal.

moringa_address_list

keyboard_arrow_down Objectives
You will be able to:

Create a list in Python


Use indexing to access elements in a list
Manipulate the items of a list
Apply hands-on list manipulation

What is a list?
keyboard_arrow_down

subdirectory_arrow_right 6 cells hidden

keyboard_arrow_down Accessing Elements in a list


In lists, which are ordered collections, we have the capability to access specific elements by
indicating their position or index. To access an element within a list, we use the list's name
followed by the index of the desired item enclosed in square brackets.

Syntax:

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 1/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

list_name[index]

Indexing in lists refers to the process of accessing or retrieving elements from a list based on
their position or index. The index of a list starts from 0 for the first element, 1 for the second
element, and so on.

For instance, if we have a list named my_list , and we want to access the element at index 2, we
would use the syntax:

my_list[2]

This method allows us, as programmers, to precisely retrieve and work with individual elements
within a list based on their positions.

# access name from student details

# modify accessed element

# example 2 - access the second element

Negative indexing starts from the end. The last element has an index of -1 , the second-
to-last has an index of -2 , and so on.

# example 3 - negative indexing

# example 4 - accessing an element in a list within a list (nested list)

We can also access a section of a list using the following syntax:

list_name[start:stop:step]

start : The starting index of the slice. It represents the first element you want in the sliced
list.
stop : The stopping index (exclusive) of the slice. It represents the first element you do not
want in the sliced list.
step (optional): The step or increment between elements. If not specified, it defaults to 1.

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 2/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

# example list

# access first three elements

keyboard_arrow_down Modifying a List


One distinctive feature of lists is their mutability, which means we can modify the elements
within a list after its creation. This mutability provides us with the flexibility to update or change
specific elements based on our needs. Modifying elements in a list is a common operation, and
it allows us to adapt our data to evolving requirements. For instance, we might have a list
representing monthly sales figures, and we could easily modify a particular element to reflect an
updated sales value or correct an error. Python's support for mutable lists empowers us as data
scientists to maintain the integrity of our datasets and adjust them dynamically as our analysis
progresses.

keyboard_arrow_down Changing Items in a List


It's common to swap out an existing item with an entirely new one. This process involves
changing elements within a list, allowing us to update information dynamically.

Syntax:

list_name[index] = new_value

# example list
fruits = ["strawberry", "pineapples"]
print(fruits)

['strawberry', 'pineapples']

# replace strawberry with oranges


fruits[0] = "oranges"
print(fruits)

['oranges', 'pineapples']

keyboard_arrow_down Adding Items to a list


In a similar vein, incorporating new elements into a list is a routine practice in Python, offering a
dynamic means to expand and update information. This process involves appending or inserting

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 3/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

elements, enabling us to seamlessly integrate fresh data into our lists. For instance, we might
need to add new observations to an existing dataset. Python provides intuitive methods for
adding elements to a list such as append() and insert() , fostering the adaptability and growth
of our lists to accommodate evolving data requirements.

append() - is a straightforward and efficient way to add items to the end of a list. By
calling the append() method on a list, we can include a new element, and it will be
automatically placed at the last position. This is particularly useful when we want to
continuously extend a list with additional data.

Syntax:

list_name.append(item)

# example using the fruit list above

# adding the fruit Mango at the end of the list

# display updated fruit list

# example 2 - adding banana

# display updated list

# example 3 - adding a list to a list

# example 4 - adding an element to a nested list

insert() - provides a flexible way to add an element at a specific position within a list.
Unlike append() , which adds the element at the end, insert() allows us to choose the
index where the new element should be placed.

syntax:

list_item.insert(index, item)

# insert apple between orange and pineapples

# display updated list

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 4/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

# add Pear at index 3

# display updated list

keyboard_arrow_down Removing Items from a list


This involves methods like pop() and remove() , allowing us to seamlessly eliminate specific
elements from our lists. Consider a scenario where we need to refine our dataset by removing
outdated or erroneous observations; Python's intuitive methods for removing elements, such as
pop() and remove() , become invaluable tools. These methods enhance the adaptability and
manageability of our lists, ensuring they remain agile and responsive to changing data needs

pop() - removes the last item from a list, providing the advantage of retaining and
allowing us to work with that removed item. Consider a list as a deck of cards, and using
pop() is akin to taking the top card off the deck. In this analogy, the top card corresponds
to the end of the list, and by popping it off, we can manipulate or examine that card
separately.

syntax:

list_name.pop()

# current list state

# remove last item

# we can work with the removed item

# display the updated list

pop(index) - allows us to remove and retrieve an item from a specific position in a list,
specified by the provided index. This method is beneficial when we want to precisely target
and work with an element from a non-terminal position within the list.

Syntax:

list_name.pop(index)

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 5/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

# remove item at index 1

# display updated list

What fruit was the latest to be removed from the list?

# work with removed element

remove() - designed to eliminate a specific value from a list. Unlike the pop() method,
which removes an element based on its index, remove() targets an element by its actual
value. This method is particularly useful when we want to delete a specific element
without knowing its position in the list.

Syntax:

list_name.remove(item_value)

# remove item with value of Pear

# display updated list

Recall

# add Mango, different case

# updated list

# remove Mango

keyboard_arrow_down Organizing a List


Creation of lists often occurs in an unpredictable order since we can't always dictate how users
input their data. While this unpredictability is common, there's a frequent need to present
information in a specific order. At times, we aim to maintain the original order of our list, while in

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 6/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

other scenarios, we intend to modify that order. Python equips us with various methods to
organize our lists based on specific situations, offering flexibility in managing the presentation
of data such as sort() and sorted() .

keyboard_arrow_down Sorting a list Permanently


sort() - permanently alters the order of the list. Once sorted, there is no way to revert to
the original order, as the changes made by sort() are applied directly to the list.

# example sales list

# sort in ascending order

# display updated list

# sort in descending order

# display updated list

keyboard_arrow_down Sorting a list Temporarily


sorted() - is a versatile alternative to the sort() method. Unlike sort() , which
permanently changes the order of the list, sorted() creates a new sorted list without
modifying the original one. This allows us to retain the original order while having a sorted
version for specific use cases.

# example

# display the list

keyboard_arrow_down Printing a List in Reverse Order


reverse() method - is a function in programming that allows us to reverse the order of
elements in a list or an array. When applied to a list, it rearranges the items in reverse

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 7/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

order, meaning the last item becomes the first, the second-to-last becomes the second,
and so on, effectively flipping the list.

We can use the reverse() method to invert the original sequence of a list. For example, if we
initially arranged the list according to the chronological order of car ownership, we can
efficiently reorganize it into a reverse chronological order.

# example 1 - list of cars

# list in reverse order

We notice that reverse() doesn't perform a backward alphabetical sort; instead, it reverses the
list's existing order. The method permanently alters the list's sequence, but we can return to the
original order at any time by applying reverse() to the same list a second time.

# applying reverse to the same list, second time

keyboard_arrow_down length of list


len() function, when used with lists, counts and returns the number of elements present
in that specific list.

By using len() with lists, we efficiently determine the quantity of items contained within the list,
enabling us to manage and manipulate the list's size as needed in our programming tasks.

Syntax

len(list_name)

# example 1 - fruits list

# example 2 - class_details list

# example 3 - len of a nested list

# example 4 - application in our code

keyboard_arrow_down Knock yourself out


https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 8/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

keyboard_arrow_down List Membership


Within our programming toolkit, the in and not in operators become indispensable when
handling lists. We utilize these operators to swiftly confirm the existence or absence of
particular elements within a list, enabling us to craft tailored responses and guide program flow
based on the presence or absence of specific values. They afford us an efficient means to
validate data and construct conditional pathways within our code.

keyboard_arrow_down Validating List Items: in Operator

in operator allows us to verify whether a specific element exists within a list.

When we use in with a list, it evaluates to True if the element is present in the list and False if
it's not found. This operator provides a straightforward way for us to confirm the existence of
elements within lists, allowing us to make decisions or perform actions based on the presence
or absence of specific values.

# example using fruits list

# check if Apples in the list

# repeat after adding Apples to the list

keyboard_arrow_down Validating List Items: not in Operator

The not in operator complements the functionality of in by allowing us to confirm the


absence of a particular element within a list.

When used with a list, not in evaluates to True if the element is not present in the list and
False if it is found.

# example

# confirm absence of watermelon

# updated list

# what happens when watermelon is present

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 9/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

keyboard_arrow_down Tuples
In this section, we'll explore tuples, a fundamental data structure in Python.

keyboard_arrow_down What is a Tuple?

A tuple is an ordered collection of elements, similar to a list, but with a crucial difference:
tuples are immutable. Once created, their contents cannot be altered or modified.

Tuples are denoted by parentheses () and can contain various data types, including integers,
strings, floats, or even other tuples.

Syntax:

tuple_name = (item_1, item_2, item_3)

# example 1

# example 2

keyboard_arrow_down Where to Use Tuples?

Tuples serve exceptionally well in situations where data integrity and immutability are
paramount. For instance, they are often used to store fixed collections of related items, such as
coordinates in geometry, dates and times, or as keys in dictionaries.

keyboard_arrow_down Differences between a tuple and a list

Aspect Lists Tuples

Mutability Mutable (Can be modified) Immutable (Cannot be modified)


Syntax Square brackets [] Parentheses ()

Modification Add, remove, and change items Cannot add, remove, or modify items
Performance Slightly slower due to mutability Slightly faster due to immutability

Use Cases Dynamic data, frequently changing elements Fixed data, maintains integrity
Denotation [item1, item2, ...] (item1, item2, ...)

keyboard_arrow_down Summary
https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 10/11
2/4/25, 3:37 PM working_with_lists.ipynb - Colab

In this lesson, we established a fundamental understanding of working with lists in Python. We


explored the dynamic nature of lists, learning how to add, remove, and modify elements within
them. The concepts of indexing, slicing, and utilizing methods like append() , insert() , pop() ,
and remove() were introduced, providing us with practical tools for effective list manipulation.
Our exploration emphasized the significance of lists in managing data and showcased Python's
flexibility in handling ordered collections. As we transition to the next lesson, we will venture into
the realm of dictionaries, further enriching our grasp of Python's versatile variable system by
exploring key-value pairs and their applications.

https://colab.research.google.com/drive/1-0IkaK-QD5fS0hJd39yyPBL-nejhjaCF#printMode=true 11/11

You might also like