Python Course - Session 04
Python Course - Session 04
-----------------------------------------------------------------------------------------------------------------------------------
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.
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.
Traversal of a List
or also
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
Copy the value from the 5th element to the 2nd element
numbers[1]=numbers[4]
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]
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.
from list[2]
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.
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).
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 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)
• 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
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)
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.
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]
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 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: [] .
list=[]
for i in range(0,10):
lista.append(i+1)
print('Obtained list: ', list)
2. Calculate the sum of the elements of the list: [9, 12, 10, 5, 30, 74]
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)
suma=0
for x in list:
sum += x
average = sum / len(list)
print('The average is: ', 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)
list[0]
for x in list:
if x > greater:
x
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:
for i in range(len(list)):
found = list[i] == value
if found:
break
if found:
Element found at index
else:
absent
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)
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
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)
Example:
create a list of five elements with the first five natural numbers raised to the
power of 3:
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.
[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)
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]
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)
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):
Matrix Exercises