Python Strutture dati: liste, tuple, insiemi e dizionari

List

  • A List è un array dinamico in Python, che consente di memorizzare più valori diversi e gli elementi possono essere modificati dopo l'inizializzazione.
  • Per dichiarare a List, usa le parentesi quadre [].

Esempio:

# Declare a List containing integers  
numbers = [1, 2, 3, 4, 5]  
  
# Access and print elements in the List  
print(numbers[0])  # Output: 1  
print(numbers[2])  # Output: 3  
  
# Modify the value of an element in the List  
numbers[1] = 10  
print(numbers)  # Output: [1, 10, 3, 4, 5]  

 

Tuple

  • A Tuple è una struttura dati immutabile in Python, spesso utilizzata per proteggere i dati dalla modifica dopo l'inizializzazione.
  • Per dichiarare un Tuple, usa le parentesi ().

Esempio:

# Declare a Tuple containing information of a student  
student_info =('John', 25, 'Male', 'New York')  
  
# Access and print elements in the Tuple  
print(student_info[0])  # Output: John  
print(student_info[2])  # Output: Male  

 

Set

  • A Set è una struttura dati che non contiene elementi duplicati e non ha ordine.
  • Per dichiarare un Set, usa le parentesi graffe {} o la set() funzione.

Esempio:

# Declare a Set containing colors  
colors = {'red', 'green', 'blue', 'red', 'yellow'}  
  
# Print the Set to check duplicate elements are removed  
print(colors)  # Output: {'red', 'green', 'blue', 'yellow'}  

 

Dictionary

  • A Dictionary è una struttura dati non ordinata che memorizza le informazioni in coppie chiave-valore.
  • Per dichiarare un Dictionary, usa le parentesi graffe {} e separa ogni coppia chiave-valore con i due punti :.

Esempio :

# Declare a Dictionary containing information of a person  
person = {'name': 'John', 'age': 30, 'city': 'New York'}  
  
# Access and print values from the Dictionary  
print(person['name'])  # Output: John  
print(person['age'])   # Output: 30  
  
# Modify the value of a key in the Dictionary  
person['city'] = 'Los Angeles'  
print(person)  # Output: {'name': 'John', 'age': 30, 'city': 'Los Angeles'}  

Queste strutture di dati consentono ai programmatori di manipolare ed elaborare i dati in modo flessibile in Python, adatto a vari scenari e scopi di programmazione.