Python Lessons – 2.8 Operations on lists

Python Lessons - 2.8 Operations on lists

Now that you have seen how to create lists, you see in this section how to apply on them some operations that will prove very useful in programming in Python.

Assigning values

Once you have defined a list with its values inside, you can later change the value of each individual element by specifying the corresponding index during a value assignment.

>>> lista = [0,1,2,3,4]
>>> lista[2] = 0
>>> lista

Arithmetic operators on lists

Two lists can be combined to form a longer one using the + operator.

>>> lista = [0,1,2,3,4]
>>> ext = [5,6]
>>> lista + ext

If instead they are multiplied by a value n, a new list will be generated containing the repetition of n times of the multiplied list.

>>> lista = [0,1,2,3,4]
>>> lista * 2
>>> [0,1,2,3,4,0,1,2,3,4]

In and Not In operators

As regards the lists, there exists the operator in which it allows to know if an element is present or not in a list, returning True if present, False if not found.

>>> lista = [0,1,2,3,4]
>>> 2 in lista
>>> 5 in lista

The opposite operation, that is, if you want to know if an element is not present, use the not in operator.

>>> lista = [0,1,2,3,4]
>>> not 2 in lista
>>> not 5 in lista

In fact, these operators are generally used with the IF command.

a = input("Inserisci un valore intero: ")
a = int(a)
lista = [0,1,2,3,4]
if a in lista:
    print("Elemento trovato")
    print("Elemento non trovato")

⇐ Go to Python Lesson 2.7 – Lists

Go to Python Lesson 2.9 – Functions on lists ⇒

Leave a Reply