DATA STRUCTURES
Before talking about the topic Lists in Python let’s make a brief introduction to the data structures in Python which are composed of:
- Lists
- Tuple
- Dictionaries
- Set
They allow you to keep not a single value as in Basic Data Types but a set of values called elements.
Lists and tuples can contain elements of any type.
- Lists are mutable
- Tuples are immutable
For example, a list can contain different elements, integers, strings, other lists. However, it is better to avoid non-heterogeneous elements, this to improve the readability of the program. The lists are mutable, that is, the objects that are part of a list can be added, modified, deleted. Conversely, once the objects they contain have been initialized, Tuples cannot be modified.
THE LISTS
type = list
Lists in Python are instances of a predefined class called list.
INSERT METHOD
APPEND METHOD
THE LISTS IN PYTHON APPEND AND INSERT METHODS VISUAL STUDIO CODE
METHOD DEL
The in operator is used to check whether an object belongs to a certain list or not.
TWO NAMES ONE LIST
If you assign a list to several variables these variables all share the same object, a change made to one variable is reflected in all the other variables. However, this is not always the desired result, with the copy method we actually split the lists, each one has its own copy.
THE COPY FUNCTION
def Lista(): mylist=[] #Crea una lista vuota mylist=[1,2,3,4,5,6] #Inizializza una lista con degli interi mylist= list() #Chiama il costruttore della classe list per #creare una lista vuota. Equivale alla prima dichiarazione. mylist=[1,2,3,4,5,6] #Si parte dall'offset 0 (indice) print(mylist[0]) print(mylist[-1]) #Se vogliamo partire dal fondo della lista usiamo #indici negativi. mylist = [[1,2],[3,4],[4,5]] #Liste di liste print(mylist[1][0]) mylist=[1,2,3,4,5,6] mylist[0] = 10 #Le liste sono oggetti mutabili. Quindi possiamo #Modificarne i valori print(mylist[0]) #SLICE DI UNA LISTA E' POSSIBILE ESTRARRE PARTI DI UNA LISTA #GLI SLICE LI ABBIAMO VISTI NELLE STRINGHE. QUI' VALGONO LE #STESSE CONSIDERAZIONI print(mylist[:2]) #ESISTE UNA FUNZIONE PREDEFINITA IN PYTHON len CHE RESTITUISCE #LA LUNGHEZZA DELLA LISTA print(len(mylist)) #INSERIMENTO DI ELEMENTI NELLA LISTA STIAMO CHIAMANDO UN METODO #DELLA CLASSE LIST CON LA DOT NOTATIONS PER INSERIRE IL NUMERO 50 #ALL'OFFSET 2 mylist.insert(2,50) mylist.append(100)#METODO APPEND AGGIUNGE IN CODA ALLA LISTA del mylist[2] #CONSENTE DI ELIMINARE UN ELEMENTO DA UNA LISTA print(100 in mylist) mylist=[1,2,3,4,5,6] #mylist2=mylist #mylist2[0]=10 mylist2=mylist.copy() mylist2[0]=10 print(mylist) print(mylist2) Lista()
Leave A Comment