0% found this document useful (0 votes)
10 views14 pages

Python Course - Session 04

The document describes lists in Python. Lists allow you to store multiple values in a variable. You can access the elements of a list by their indices and modify them. There are methods such as append(), insert(), sort(), reverse() to add, insert, sort, and reverse elements in a list.
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)
10 views14 pages

Python Course - Session 04

The document describes lists in Python. Lists allow you to store multiple values in a variable. You can access the elements of a list by their indices and modify them. There are methods such as append(), insert(), sort(), reverse() to add, insert, sort, and reverse elements in a list.
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/ 14

Python Course

-----------------------------------------------------------------------------------------------------------------------------------
LISTS
We are going to create a variable called numbers; it is assigned not only a number, but it is filled.
with a list that consists of five values (note: the list starts with an open bracket and
ends with a closed bracket; the space between the brackets is filled with five numbers
separated by commas.

lista de numeros : [10, 5, 7, 2, 1]

Let's say the same using appropriate terminology: numbers is a list consisting of
five values, all of them numbers. We can also say that this statement creates a list of
length equal to five (since it contains five elements).

The elements in a list can have different types. Some of them can be
some are integers, others are floats, and others can be lists.

Python has adopted a convention that indicates that the elements of a list are always
numbered from zero. This means that the element stored at the beginning of the list will have the
zero. As there are five elements in our list, the last of them is assigned the number
four. Don't forget this.

Before continuing with our discussion, we must point out the following: our list is a
collection of elements, but each element is a scalar.

The len function

The len function returns the number of elements currently stored

Traversal of a List

It can be done in several ways:

or also

Print the elements of the list one on each line

Teacher: Eng. Marcelino Torres Villanueva Page 1


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
Operations with lists

Change the value of an element in a list


Here is the list

numeros = [10, 5, 7, 2, 1]
We are going to assign a new value of 89 to the first element in the list.

We do it this way:

numeros[0]=89

The new list will be: [89, 5, 7, 2, 1]

Copy the value from the 5th element to the 2nd element

numbers[1]=numbers[4]

the new list will be: [89, 1, 7, 2, 1]

The value within the brackets that selects an element from the list is called an index, while
the operation of selecting an element from the list is known as indexing.

numeros = [10, 5, 7, 2, 1]

print("Content of the list:", numbers)

Removing an element from the List

Any item in the list can be removed at any time, this is done with a
instruction call (delete). Note: it is an instruction, not a function.

IF we have the list

lista = [20, 40, 90,5, 36, 28]

If we want to remove the third element, we place

from list[2]

We will execute the following program:

Teacher: Ing. Marcelino Torres Villanueva Page 2


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
Negative indices are valid.

An element with an index of -1 is the last in the list

Similarly, the element with an index of -2 is the one before the last in the list.

Exercise

Once upon a time there was a hat. The hat did not contain a rabbit, but a list of five numbers: 1, 2,
3, 4 and 5.

Your task is:

Write a line of code that asks the user to replace the central number in the list.
with an integer number entered by the user (step 1).

Write a line of code that removes the last element from the list (step 2).

Write a line of code that prints the length of the existing list (step 3).

Add an element to a List: Append method

A new element can be added to the end of the existing list:

list.append(value)

This operation is performed using a method called append(). It takes the value of its argument
and it places it at the end of the list that has the method

The length of the list increases by one.

Insert an element into a list: Insert method

The insert() method is a bit smarter: it can add a new element anywhere.
place on the list, not just at the end.

list.insert(location,value)

Takes two arguments:

• The first shows the required location of the element to be inserted. Note: all
existing elements that occupy locations to the right of the new element (including the

Teacher: Eng. Marcelino Torres Villanueva Page 3


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
that is in the indicated position) shift to the right, to make space for the
new element.
• The second is the element to be inserted.

If we have the following code:

valores=[2, 35, 78,45, 94, 13]


values.append(10)
print(values)
values.insert(3,21)
print(values)
The result will be:
[2, 35, 78, 45, 94, 13, 10]
[2, 35, 78, 21, 45, 94, 13, 10]

Empty List
We can initialize a list in the following way:
list =[]

Invert a list
There is also a list method called reverse(), which you can use to reverse the list, by
example:
lst = [5, 3, 1, 2, 4]
print(lst)
lst.reverse()
[4, 2, 1, 3, 5]

Sort a List
To sort a list, the sort method is used.
Example:
lista=[12, 5, 10, 4, 30]
print('Initial List: ', list)
list.sort()
print('Sorted list: ', list)

Teacher: Eng. Marcelino Torres Villanueva Page 4


Python Course
-----------------------------------------------------------------------------------------------------------------------------------

Assignment of one list to another


The name of a list is the name of a memory location where the list is stored.
When you assign one list to another, you copy the memory address of the list.
Example:
lista1=[20, 5, 80, 42]
list2=list1
The assignment list2=list1 copies the name of list1 to list2, not its content.
Example:

The result will be:


Lista 1: [20, 5, 80, 42]
Lista 2: [20, 5, 80, 42]
Lista 1: [15, 5, 80, 42]
Lista 2: [15, 5, 80, 42]
List1 and list2 point to the same list. If any changes are made to the list, when printing both lists,
these will be the same.

The operators in and not


Python offers two very powerful operators, capable of checking the list to verify if a value
whether a specific item is stored within the list or not.
These operators are:
removeList
element not in myList

The first of them (in) checks if a given element (its left argument) is currently
stored somewhere within the list (the right argument) - the operator returns True
in this case.
The second (not in) checks if a given element (its left argument) is absent in a
list - the operator returns True in this case.

Slices
A slice is an element of Python syntax that allows you to make a new copy of a
list, or parts of a list.
In fact, copy the contents of the list, not the name of the list.

Teacher: Eng. Marcelino Torres Villanueva Page 5


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
The syntax is as follows:
myList[start:end]
A slice of this type creates a new list (destination), taking elements from the source list:
the elements of the indices from the beginning to the end-1.
Example:
miLista = [10, 8, 6, 4, 2]
newList = myList [1:3]
print(newList)
result
[8, 6]

Using myList[:] creates a new copy of all the content in the list.
Example

Result:
Lista 1: [20, 5, 80, 42]
Lista 2: [20, 5, 80, 42]
Lista 1: [20, 5, 80, 42]
Lista 2: [15, 5, 80, 42]
By doing the assignment list2=list1[:], we copy the contents of list1 to list2, which means
that list1 and list2 are two different memory locations. If a change is made in either one
one does not affect the other.

If you omit the start in your slice, it is assumed that you want to get a segment that starts at the
element with index 0.
In other words, the slice would be like this: myList[:end]
It's a more compact equivalent: myList[0:end]
Example:
miLista = [10, 8, 6, 4, 2]
newList = myList[:3]
print(newList)
Result
[10, 8, 6]

Teacher: Eng. Marcelino Torres Villanueva Page 6


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
If you omit the end in your slice, it is supposed that you want the segment to end at the element with
the index len(myList).
In other words, the slice would be like this: myList[start:]
It is a more compact equivalent: myList[start:len(myList)]
Example:
miLista = [10, 8, 6, 4, 2]
newList = myList[3:]
print(newList)
Result
[4, 2]

Slices with negative indices

miLista = [10, 8, 6, 4, 2]
newList = myList[1:-1]
print(newList)
The result of the fragment is: [8, 6, 4].

If the beginning specifies an element that is beyond that described by the end (from the point of
initial view of the list), the slice will be empty:

miLista = [10, 8, 6, 4, 2]
newList = myList[-1:1]
print(newList)

The output of the fragment is: [].

The instruction described above can remove more than one element from the list at once,
it can also remove slices:
Example:
miLista = [10, 8, 6, 4, 2]
from myList[1:3]
print(myList)
Result
[10, 4, 2].
All elements can be deleted at once.
Example:
miLista = [10, 8, 6, 4, 2]
from myList[:]
print(myList)
The list is empty and the output is: [] .

Teacher: Eng. Marcelino Torres Villanueva Page 7


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
List Exercises

1. Create a list that has the numbers from 1 to 10

list=[]
for i in range(0,10):
lista.append(i+1)
print('Obtained list: ', list)

The output will be:


List obtained: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2. Calculate the sum of the elements of the list: [9, 12, 10, 5, 30, 74]

numeros=[9, 12, 10, 5, 30, 74]


sum=0
for x in numbers:
sum += x
print('The sum of the elements in the list is:', suma)

The result is:


The sum of the elements of the list is: 140

3. Enter n real elements into a list. Print the elements of the list one per line and then
calculate their average.

while True:
n=int(input('Number of elements in a list: '))
if n>0:
break
list=[]
for i in range(0,n):
x = float(input('Enter number:'))
list.append(x)

Print('Elements of the list')


for x in list:
print(x)

suma=0
for x in list:
sum += x
average = sum / len(list)
print('The average is: ', average)

Instructor: Eng. Marcelino Torres Villanueva Page 8


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
4. Enter n elements into a list and calculate the greatest of them

while True:
n=int(input('Number of elements in a list: '))
if n>0:
break
list=[]
for i in range(0,n):
x=float(input('Enter number:'))
list.append(x)

print('Entered list: ', list)

list[0]
for x in list:
if x > greater:
x

print('The largest is: ', largest)

5. Enter n elements into a list, then enter a value and then indicate at what position it is.
find from the list or indicate that it is not found.

while True:
n=int(input('Number of elements in a list: '))
if n > 0:
break
lista=[]
for i in range(0,n):
x=float(input('Enter number:'))
list.append(x)

Input list:

value=float(input('Value to search for: '))


found = False

for i in range(len(list)):
found = list[i] == value
if found:
break

if found:
Element found at index
else:
absent

Teacher: Eng. Marcelino Torres Villanueva Page 9


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
6. Enter n elements into a list and then sort it using the bubble sort method.

while True:
n=int(input('Number of elements in a list: '))
if n>0:
break
list=[]
for i in range(0,n):
x=int(input('Enter number:'))
list.append(x)

print('Entered List: ', list)

for i in range(0,n-1):
j=len(list)-1
while j>i:
if list[j] < list[j-1]:
lista[j], lista[j-1] = lista[j-1], lista[j]
j=j-1

print('Sorted list: ', list)

7. Enter a list of n real numbers and in the end obtain a list without duplicate data.
The objective is to have a list in which all numbers appear no more than once.

while True:
n=int(input('Number of elements in a list: '))
if n > 0:
break
list=[]
for i in range(0,n):
x=int(input('Enter number:'))
lista.append(x)

print('Entered List: ',list)


i=0
while i<len(list):
j=i+1
while j < len(lista):
if list[i] == list[j]:
from list[j]
j=j-1
j=j+1
i=i+1
print("The list with unique elements only:")
print(list)

Teacher: Eng. Marcelino Torres Villanueva Page 10


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
List Comprehension
List comprehension allows you to create new lists from existing ones in a way
concise and elegant. The syntax of a list comprehension is as follows:
[expression for element in list if conditional]

Which is an equivalent of the following code:


for element in list:
if conditional:
expression

Example:
create a list of five elements with the first five natural numbers raised to the
power of 3:

salida:[0, 1, 8, 27, 64]

salida:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


[1, 9, 25, 49, 81]

Proposed exercises on Lists

1) Enter n integers into a list and then show, first the list of numbers.
pairs that were entered and then the list of negative numbers.
2) Enter n integers into a list A and another n integers into a list B and display the list of
elements of the vector C. Where each C[i]=A[i]+B[i].
3) Calculate the harmonic mean of a dataset. The harmonic mean is defined as: the
Inverse of the average of the inverses.
4) Let it be a list of n real elements. Show the list of numbers less than the average.
5) Enter N grades in a list and determine the percentage of approvals and the percentage of
disapproved.
6) Enter n elements into a list and then enter an element and report how many times it appears.
that element appears in the list
Enter two lists and report if they are the same.
8) Calculate the median of a data set. The median of an ordered vector is the
central element if the number of terms is odd. And the semi-sum of the terms
central if the number of terms is even.
9) Enter 2 lists of n and m elements and calculate the union, intersection, and difference of
first with the second.

Teacher: Eng. Marcelino Torres Villanueva Page 11


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
Matrices in Python
Nested lists can be used in Python to create matrices (that is, two-dimensional lists).
example:
This code creates a matrix with 3 rows, and each row has the numbers from 1 to 8.
datos =[[num for num in range (1,9)] for j in range(3)]
for row in data:
print(row)
The result is:

[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
The notation datos[i][j] can be used to access the element at row i and column j.

Matrix Exercises
1. Create a program to enter f rows and c columns into a matrix. Calculate the largest, the
minimum and the average.
while True:
f=int(input('Number of rows:'))
if f>0:
break
while True:
c=int(input('Number of columns:'))
if c>0:
break
matrix=[]
for i in range(f):
queue = []
for j in range(c):
print('matrix[',i,'][',j,']:',sep='',end='')
value=int(input())
fila.append(value)
matrix.append(row)

for row in matrix:


print(line)

mayor=matrix[0][0]
for row in matrix:
for x in row:
if x > mayor:
x
print('The largest is: ', largest)

least=matrix[0][0]

Teacher: Eng. Marcelino Torres Villanueva Page 12


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
for row in matrix:
for x in row:
if x<less:
smaller
print('The smallest is: ', menor)

suma=0
for row in matrix:
for x in row:
suma += x
sum/(f*c)
print('The average is: ', average)

2. Enter a matrix with f rows and c columns and find the sum of the rows and the sum of
columns.
while True:
f=int(input('Number of rows:'))
if f > 0:
break

while True:
c=int(input('Number of columns:'))
if c>0:
break

matrix=[]
for i in range(f):
queue=[]
for j in range(c):
print('matrix[',i,'][',j,']:',sep='',end='')
value=int(input())
queue.append(value)
matrix.append(row)

for row in matrix:


print(queue)

i=0
for row in matrix:
sf=0
for x in row:
sf+=x
Sum of row 'i' = sf
i=i+1

for j in range(c):

Teacher: Eng. Marcelino Torres Villanueva Page 13


Python Course
-----------------------------------------------------------------------------------------------------------------------------------
sc=0
for i in range(f):
sc += matrix[i][j]
Sum of column

Matrix Exercises

Enter a matrix of f rows and c columns and calculate its transpose.


2. Enter a matrix and report the largest element of each row
3. Program to enter a matrix of f rows and c columns, then enter a number
column and remove it from the matrix
4. Program to enter a matrix of f rows and c columns, then enter the row number
and insert a row into the matrix.
5. Enter a matrix with f rows and c columns and then exchange 2 columns of the matrix. The
The number of the columns to be swapped must be entered.
6. Program that inputs the order of a square matrix and generates it and then makes the
next:
a) Calculate the sum of the elements of the main diagonal.
b) Calculate the average of the elements of the secondary diagonal
7. Enter a square matrix and report if it is symmetric. Remember that a matrix is
symmetric if the condition is met: a[i][j]=a[j][i]
8. Program to enter a matrix with f rows and columns and then sort the columns of the
matrix.

Teacher: Eng. Marcelino Torres Villanueva Page 14

You might also like