Cos’è una lista in informatica?

Una lista è una struttura dati comune nella maggior parte dei linguaggi di programmazione.

Funziona come una collezione di elementi. Come minimo, di solito fornisce la possibilità di aggiungere o rimuovere elementi alla fine della lista, e di cercare elementi in una particolare posizione nella lista.

Per esempio, in Python, si può creare una lista usando le parentesi quadre.

  1. x = [1, 2, 3] # Declare a new list 
  2. x.append(4) # Add 4 to the end of the list 
  3. print(x) # Print the entire list 
  4. >> [1, 2, 3, 4] 
  5. x[0] = 5 # Lists are indexed from 0, so this changes the beginning. 
  6. print(x) 
  7. >> [5, 2, 3, 4] 

In Java, the most commonly used list is the ArrayList in the standard library. As part of the declaration, you have to say what kind of data type you’re going to store in the list.

  1. ArrayList array = new ArrayList<>(); // Make list of integers 
  2. array.add(1); // Add 1 to the end of the list 
  3. array.add(2); // Add 2 to the end of the list 
  4. System.out.println(array.get(1)); // As in Python, ArrayLists are indexed from 0, so this returns the second item. 
  5. >> 2