logo

Come scorrere una lista in Python

Le liste sono una delle strutture dati più utilizzate in Python. Continuiamo a utilizzare gli elenchi in molte applicazioni diverse, dalla risoluzione di problemi semplici a problemi complessi. In Python, gli elenchi sostituiscono gli array con vantaggi come:

  1. Dimensioni dinamiche
  2. Può memorizzare elementi di diversi tipi di dati in un unico elenco

Possiamo accedere ai dati semplicemente da elenchi ordinati; a differenza dei set, i dati non saranno ordinati. Per accedere ai dati, possiamo utilizzare diversi modi per scorrere ciascun elemento all'interno di un elenco. Questo tutorial copre tutti i modi con esempi.

1. Circuiti

    Utilizzo del ciclo while:
 list1 = [3, 5, 7, 2, 4] count = 0 while (count <len(list1)): 1 print (list1 [count]) count="count" + < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>We created a list with a few elements. Initially, count = 0. We&apos;re printing the element at the &apos;count&apos; index and incrementing the count in the while loop. When the count reaches the length of the list, the loop will be terminated, and all the elements will already be accessed.</p> <p> <strong>Mechanism:</strong> </p> <table class="table"> <tr> <td>count = 0</td> <td>list1 [0]</td> <td>3</td> </tr> <tr> <td>count = 1</td> <td>list1 [1]</td> <td>5</td> </tr> <tr> <td>count = 2</td> <td>list1 [2]</td> <td>7</td> </tr> <tr> <td>count = 3</td> <td>list1 [3]</td> <td>2</td> </tr> <tr> <td>count = 4</td> <td>list1 [4]</td> <td>4</td> </tr> <tr> <td>count = 5 = len (list1)</td> <td>-</td> <td>-</td> </tr> </table> <ul> <tr><td>Using for loop:</td>  </tr></ul> <pre> list1 = [3, 5, 7, 2, 4] for i in list1: print (i) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-2.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>Using for-in, we accessed all the i&apos;s, the elements inside the list.</p> <ul> <tr><td>Using for and range:</td>  </tr></ul> <pre> list1 = [3, 5, 7, 2, 4] length = len (list1) for i in range (0, len (list1)): print (list1 [i]) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-3.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>The range function helps the &apos;for&apos; loop to iterate from 0 to the given list&apos;s length.</p> <p> <strong>Mechanism:</strong> </p> <table class="table"> <tr> <td>the range gives - 0</td> <td>list1 [0]</td> <td>3</td> </tr> <tr> <td>the range gives - 1</td> <td>list1 [1]</td> <td>5</td> </tr> <tr> <td>the range gives - 2</td> <td>list1 [2]</td> <td>7</td> </tr> <tr> <td>the range gives - 3</td> <td>list1 [3]</td> <td>2</td> </tr> <tr> <td>the range gives - 4</td> <td>list1 [4]</td> <td>4</td> </tr> </table> <ul> <li>The range function doesn&apos;t give the last element specified - len (list1) = 5 is not given.</li> </ul> <h2>2. Using List Comprehension</h2> <p>This is the simple and suggested way to iterate through a list in Python.</p> <p> <strong>Code:</strong> </p> <pre> list1 = [3, 5, 7, 2, 4] [print (i) for i in list1] print (&apos;
&apos;) [print (list1 [i]) for i in range (0, len (list1))] print (&apos;
&apos;) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-4.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>We can use for loops inside a list comprehension. We used the same for loops we used in the above examples but inside a list in a single line. This way, we can reduce the length of the code and also list comprehension is a very subtle and efficient way to put loops in lists.</p> <h2>3. Using enumerate():</h2> <p>The enumerate function converts the given list into a list of tuples. Another important fact about this function is that it keeps count of the iterations. This is a built-in function in Python.</p> <p> <strong>Code:</strong> </p> <pre> list1 = [3, 5, 7, 2, 4] for i, j in enumerate (list1): print (&apos;index = &apos;, i, &apos;value: &apos;, j) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-5.webp" alt="How to Iterate through a List in Python"> <h2>4. Using lambda function and map():</h2> <p>These are anonymous functions. There is a function map () in Python that can accept a function as an argument, and it calls the function with every element in the iterable, and a new list with all the elements from the iterable will be returned.</p> <p> <strong>Code:</strong> </p> <pre> list1 = [3, 6, 1, 8, 7] result = list (map (lambda num: num, list1)) print (result) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-6.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>The lambda num: num is given as an input to the map function along with the list. The function will take every single element in the list, accept it, and then return it. The map () function will pass the list elements one by one to the lambda function to return the elements.</p> <h2>What if we want to Iterate Multi-dimensional Lists?</h2> <p>There is an inbuilt module in Python designed to perform operations on multi-dimensional lists.</p> <p> <strong>1. To get numpy:</strong> </p> <p>Check if Python and pip are installed by opening the cmd via search and typing the commands:</p> <p> <strong>Python -version</strong> </p> <p> <strong>Pip --version</strong> </p> <p>If both Python and PIP are present in our system, it is now time to install our library:</p> <p> <strong>2. Open cmd from the start menu</strong> </p> <p> <strong>3. Type the command</strong> </p> <h3>pip install numpy</h3> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python.webp" alt="How to Iterate through a List in Python"> <p>All the library packages, data, and sub-packages will be installed one after the other.</p> <p> <strong>Code:</strong> </p> <pre> import numpy list1 = numpy. arange (9) list1 = list1. reshape (3, 3) for x in numpy. nditer (list1): print (x) </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/python-tutorial/43/how-iterate-through-list-python-7.webp" alt="How to Iterate through a List in Python"> <p> <strong>Understanding:</strong> </p> <p>We imported the numpy module. Using the arrange method, we created an array with 9 elements. We accessed the list by reshaping it to 3 * 3 (rows * columns) using the reshape. Using the nditer function, we printed each element in the list.</p> <hr></len(list1)):>

Produzione:

Come scorrere una lista in Python

Comprensione:

Usando for-in, abbiamo avuto accesso a tutte le i, gli elementi all'interno della lista.

    Utilizzo per e intervallo:
 list1 = [3, 5, 7, 2, 4] length = len (list1) for i in range (0, len (list1)): print (list1 [i]) 

Produzione:

Come scorrere una lista in Python

Comprensione:

La funzione range aiuta il ciclo 'for' a scorrere da 0 alla lunghezza dell'elenco specificato.

sindacato contro sindacato tutto

Meccanismo:

l'intervallo dà - 0 foglio1 [0] 3
l'intervallo dà - 1 foglio1 [1] 5
l'intervallo dà - 2 foglio1 [2] 7
l'intervallo dà - 3 foglio1 [3] 2
l'intervallo dà - 4 foglio1 [4] 4
  • La funzione range non fornisce l'ultimo elemento specificato: len (list1) = 5 non viene fornito.

2. Utilizzo della comprensione delle liste

Questo è il modo semplice e suggerito per scorrere un elenco in Python.

Codice:

 list1 = [3, 5, 7, 2, 4] [print (i) for i in list1] print (&apos;
&apos;) [print (list1 [i]) for i in range (0, len (list1))] print (&apos;
&apos;) 

Produzione:

Come scorrere una lista in Python

Comprensione:

casting del tipo e conversione del tipo in Java

Possiamo usare i cicli for all'interno di una lista di comprensione. Abbiamo utilizzato gli stessi cicli for utilizzati negli esempi precedenti ma all'interno di un elenco in un'unica riga. In questo modo, possiamo ridurre la lunghezza del codice e anche la comprensione delle liste è un modo molto sottile ed efficiente per inserire cicli nelle liste.

3. Utilizzando enumerate():

La funzione enumerate converte l'elenco fornito in un elenco di tuple. Un altro fatto importante di questa funzione è che tiene il conto delle iterazioni. Questa è una funzione incorporata in Python.

Codice:

 list1 = [3, 5, 7, 2, 4] for i, j in enumerate (list1): print (&apos;index = &apos;, i, &apos;value: &apos;, j) 

Produzione:

Come scorrere una lista in Python

4. Utilizzando la funzione lambda e map():

Queste sono funzioni anonime. Esiste una funzione map () in Python che può accettare una funzione come argomento e chiama la funzione con ogni elemento dell'iterabile e verrà restituito un nuovo elenco con tutti gli elementi dell'iterabile.

Codice:

 list1 = [3, 6, 1, 8, 7] result = list (map (lambda num: num, list1)) print (result) 

Produzione:

Come scorrere una lista in Python

Comprensione:

Il lambda num: num viene fornito come input alla funzione map insieme all'elenco. La funzione prenderà ogni singolo elemento nell'elenco, lo accetterà e quindi lo restituirà. La funzione map() passerà gli elementi della lista uno per uno alla funzione lambda per restituire gli elementi.

Cosa succede se vogliamo iterare elenchi multidimensionali?

Esiste un modulo integrato in Python progettato per eseguire operazioni su elenchi multidimensionali.

1. Per diventare insensibile:

Controlla se Python e pip sono installati aprendo il cmd tramite ricerca e digitando i comandi:

Versione Python

Pip --versione

Se nel nostro sistema sono presenti sia Python che PIP, è giunto il momento di installare la nostra libreria:

array ordinato in Java

2. Apri cmd dal menu Start

3. Digitare il comando

pip installa numpy

Come scorrere una lista in Python

Tutti i pacchetti della libreria, i dati e i sottopacchetti verranno installati uno dopo l'altro.

Codice:

 import numpy list1 = numpy. arange (9) list1 = list1. reshape (3, 3) for x in numpy. nditer (list1): print (x) 

Produzione:

Come scorrere una lista in Python

Comprensione:

Abbiamo importato il modulo Numpy. Utilizzando il metodo organizzare, abbiamo creato un array con 9 elementi. Abbiamo effettuato l'accesso all'elenco rimodellandolo in 3 * 3 (righe * colonne) utilizzando il rimodellamento. Usando la funzione nditer, abbiamo stampato ogni elemento nell'elenco.