You are on page 1of 37

Python - Lists and tuples

Introduction
- So far you have interacted with data types
including int, bool, float and string.
- Today, we are introducing new compound data
types
- Lists
- Tuples
- We will look into methods and functions
associated with these data structures.
- We will look into the idea of aliasing, cloning and
mutability
List
● Ordered sequence of information, accessible by
index.
● a list is denoted by square brackets, []
● a list contains elements
○ usually homogeneous (ie, all integers or all strings)
○ can contain mixed types (not common)
○ list elements can be changed so a list is mutable
● Creating a list:
○ Create an empty list
ages = [] ⇔ empty brackets
ages = list() ⇔ type constructor
○ Creating a list of with elements:
ages = [87, 23, 1, 98] ⇔ using the brackets
ages = 87, 23, 1, 98 ⇔ declare a tuple
list_ages = list(ages) ⇔ use the list constructor
to convert the tuple to a list.
● Unlike arrays, Lists can used to store different types of
data:

engineers = [10, “Otto”, “Mocheko”, “Nathaniel”, 50, 72, “M”]

● Access Python List Elements: Indexing


Each item in a list is associated with a number. The number
is known as a list index.We can access elements of an array
using the index number (0, 1, 2 …).
>>> languages = [“C”, “Bash”, “Python”, “JavaScript”,
“Java”]

>>> languages[0] ⇔ # evaluates to “C”

>>> languages[3] ⇔ # evaluates to “JavaScript”

>>> languages[9] ⇔ out of range error


● Negative indexing:
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the
second last item and so on.

>>> languages = [“C”, “Bash”, “Python”,


“JavaScript”, “Java”]
>>> languages[-1] ⇔ evaluates to “Java”
>>> languages[-2] ⇔ evaluates to “JavaScript”
● Slicing a list:
it is possible to access a section of items from the
list using the slicing operator :, not just a single
item. For example,
>>> languages = [“C”, “Bash”, “Python”, “JavaScript”,
“Java”, “C++”, “Golang”, “Dart”]
>>> languages[0:3] # returns a list with items from index
0 to index 2.
>>> languages[2:] # returns a list with items from index
2 to the last item in the list
>>> languages[:] #returns a list with all the items
>>> languages[1:7:2] # returns a list with items jumping
two items.
Changing Items in a list
● lists are mutable!
● assigning to an element at an index changes the value,
for instance
my_list = [2, 1, 3, 4]
my_list[1] = 5
my_list is now [2, 5, 3, 4], note this is the same object
my_list
Iterating over a list
- For instance, if you are to add the sum of all items
in a list you may need to iterate through the list
elements in order to achieve this.
- There are two ways you can do this.
- You can use the index as shown below
def sum_of_elements(my_list):
total = 0
for i in range(len(my_list)):
total += my_list[i]
return total
Iterating over a list
- There are two ways you can do this.
- You can iterate over the elements directly as you would a
string
def sum_of_elements(my_list):
total = 0
for i in my_list:
total += i
return total
- list elements are indexed 0 to len(L)-1
- range(n) goes from 0 to n-1
Operations on a list
● Add an element to a list:
- append() - this method adds an element to the
list, syntax list_name.append(element). For
instance,
>>> my_list = [5, 2, 4]
>>> my_list.append(3)
>>> print(my_list) ⇔ # [5, 2, 4, 3]
- extend() - use this method to combine two lists. We
can use the + operator too
list_1 = [5, 2, 4] list_2 = [ 6, 9, 5]
>>> list_1.extend(list_2) # [5,2,4,6,9,5]
>>> list_1 is mutated
● Inserting element at an index:
insert() - The insert() method inserts an element
to the list at the specified index.
Syntax:
list_name.insert(index, element)
>>> my_list = [3, 4,2, 1]
>>> my_list.insert(2, 0)
>>> my_list
Operations on a list
● Remove an element from a list:
- delete an element at a specific index
del my_list[index]
- remove an element at the end of the list,
my_list.pop()
# returns the removed element.
- remove a specific element with
my_list.remove(element)
- Looks for the element and removes it
○ if element occurs multiple times, removes first
occurrence
○ if element not in list, gives an error
Examples
● Create a list with numbers
numbers = [5, 10, 15, 20, 25]
print(numbers)
print("numbers[0]: {} numbers[2]: {}".format(numbers[0], numbers[2]))

● Create a list with strings


names = ["Elijah", "Osei", "Olamide"]
print(names)
print("names[0]: {} namdes[2]: {}".format(names[0], names[2]))

● Create a list with different data types


diff_types = [10, "Otto", "Mocheko", "Nathaniel", 50, 72, 89]
print(diff_types)
print ...
Creating list with range()
>>> num = list(range(4, 9, 2))
>>> print(num)
[4, 6, 8]
Updating list
● Creation
>>> lst = list(range(1, 5))
>>> print(lst)
[1, 2, 3, 4]
● Append
>>> lst.append(9)
>>> print(lst)
[1, 2, 3, 4, 9]
Updating List
● Update - 1
>>> lst[1] = 8
>>> print(lst)
[1, 8, 3, 4, 9]
● Update - 2
>>> lst[1: 3] = 10, 11
>>> print(lst)
[1, 10, 11, 4, 9]
Updating a list
● Delete
>>> del lst[1]
>>> print(lst)
[1, 11, 4, 9]
● Remove
>>> lst.remove(11)
>>> print(lst)
[1, 4, 9]
● Reverse
>>> lst.reverse()
>>> lst
[9, 4, 1]
Concatenation of two lists
● “+” Operator is used to join two lists
>>> lst1 = [5, 10, 15]
>>> lst2 = [20, 25]
>>> print(lst1 + lst2)
[5, 10, 15, 20, 25]
Repetition of List
● “*” is used to repeat the list ‘n’ times
>>> nums = [10, 20, 30]
>>> print(nums * 2)
[10, 20, 30, 10, 20, 30]
Membership of a list
● “In” and “not in” operators are used to check,
whether an element belongs to the list or not
x = [1, 2, 3, 4, 5, 6]
a = 2
print(a in x) # Returns True, if the item is found in the List

x = [1, 2, 3, 4, 5, 6]
a = 7
print(a not in x) # Returns True, if the item is not found in
the list
Aliasing and cloning Lists
● Giving a new name for the existing list
○ This method does not copy the list but rather copies the
reference of the list to the second variable.
x = [20, 30, 40]
y = x # In this case, No separate memory will be allocated for y

● Cloning / Making a copy


>>> x = [10, 20, 30, 40, 50]
>>> y = x[:]
>>> x[1] = 100
>>> print(x)
[10, 100, 30, 40, 50]
>>> print(y)
[10, 20, 30, 40, 50]
# Note: Changes made in one list will not reflect on the other
Aliasing and cloning Lists
● Copying a list will only allow primitive values in the list
to be copied.
● To copy a nested list, a different approach must be
used.
○ One is to use the copy module.

>>> old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> new_list = old_list.copy()
>>> old_list.append([4, 4, 4])
>>> print("New list:", new_list)
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(“Old list:”, old_list)
Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 4, 4]]

○ As you can see, the old value being changed does not affect
the newly copied list.
To find the common items
# To find the common item given two lists

lst = ["Alex", "Abdul", "Phillip", "Janet"]


lst2 = ["Amos", "Phillip", "Leonex", "Fazul"]

# Convert them into sets


lst = set(lst)
lst2 = set(lst2)

# Filter intersection of two sets


lst3 = lst.intersection(lst2)

# Convert back into the list


common = list(lst3)

print(common)
Nested List
# To create a list with another list as element

lst = [5, 10, 15, [40, 50]]


print(lst)
List Comprehensions
● Creation of new list from an iterable object (set tuple,
dictionary, list or range) that satisfies a given
condition
# Create a list with squares of integers from 1 to 5

[expression for loop condition]


# Method 1
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares)

# Method 2
squares = []
squares = [i ** 2 for i in range(1, 6)]
print(squares)
List Comprehensions

# Get even squares from 1 to 10

even_squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]


print(even_squares)
List Comprehensions
# Adding the elements of two list one by one

x = [10, 20, 30]


y = [1, 2, 3, 4]

lst = []

# Method 1
for i in x:
for j in y:
lst.append(i + j)

# Method 2
lst = [i + j for i in x for j in y]

# concatenate two lists


lst = [i + j for i in "ABC" for j in "DE"]
print(lst)
Exercise
● Reverse the elements of a list
● Find the minimum and maximum element in a list
of elements
● Check how many times an element occurs in a
list
● Create a languages list and search for a
particular language
Tuple
● A tuple is similar to list but is immutable
Creating tuples
To create empty tuple
tup1 = ()

Tuple with one item


tup2 = (10, )

Tuple with different dtypes


tup3 = (10, 20, 2.3, "Jonnes", "M")

Tuple with no braces


tup4 = 5, 20, 35, 50

Create a tuple from the list


lst = [10, 20, 2.3, "Jonnes", "M"]
tup5 = tuple(lst)

Create tuple from range


tup6 = tuple(range(10))
Accessing Tuples
● Accessing items in the tuple can be done by
indexing or slicing method, similar to that of list
Basic Operations On Tuples
s = (10, "Jonnes", 10, 20, 30, 40, 50)

To find the length of the tuple


print(len(s))

Repetition operator
mark = (25.000, ) * 4
print(mark) # (25.0, 25.0, 25.0, 25.0)

Concatenate the tuples using +


co = s + mark
print(co) # (10, 'Jonnes', 10, 20, 30, 40, 50, 25.0, 25.0,
25.0, 25.0)
Functions To Process Tuples
● len() - len(tpl) - Returns the number of elements in the tuple

● max() - max(tpl) - Returns the biggest element in the tuple

● min() - min(tpl) - Returns the smallest element in a tuple

● count() - tpl.count(x) - Returns how many times the element


'x' is found in the tuple

● index() - tpl.index(x) - Returns the first occurence of the


element x in tuple. If not found, Raises ValueError

● sorted() - sorted(tpl) - Sorts the elements of the tuple into


ascending order sorted(tuple_name, reverse=True) will sort in
reverse order
Exercise
● Find the occurrence of an element in a tuple
● Insert a new item into a tuple at a specified
location
● Replace an existing element of a tuple with new
element
● Delete an element from a particular position in
the tuple
See you at
the next
session!

You might also like