logo

Hoe u door een lijst in Python kunt bladeren

Lijsten zijn een van de meest gebruikte datastructuren in Python. We blijven lijsten gebruiken in veel verschillende toepassingen, van het oplossen van eenvoudige problemen tot complexe problemen. In Python vervangen lijsten arrays met voordelen zoals:

  1. Dynamisch van formaat
  2. Kan items van verschillende gegevenstypen in één lijst opslaan

We hebben eenvoudig toegang tot de gegevens via lijsten zoals besteld; Anders dan bij sets zijn de gegevens ongeordend. Om toegang te krijgen tot de gegevens kunnen we verschillende manieren gebruiken om elk element in een lijst te doorlopen. Deze tutorial behandelt alle manieren met voorbeelden.

1. Lussen

    While-lus gebruiken:
 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)):>

Uitgang:

Hoe u door een lijst in Python kunt bladeren

Begrip:

Met behulp van for-in hebben we toegang gekregen tot alle i's, de elementen in de lijst.

    Gebruik voor en bereik:
 list1 = [3, 5, 7, 2, 4] length = len (list1) for i in range (0, len (list1)): print (list1 [i]) 

Uitgang:

Hoe u door een lijst in Python kunt bladeren

Begrip:

De bereikfunctie helpt de 'for'-lus te itereren van 0 naar de lengte van de gegeven lijst.

np.waar

Mechanisme:

het bereik geeft - 0 blad1 [0] 3
het bereik geeft - 1 blad1 [1] 5
het bereik geeft - 2 blad1 [2] 7
het bereik geeft - 3 blad1 [3] 2
het bereik geeft - 4 blad1 [4] 4
  • De bereikfunctie geeft niet het laatst opgegeven element - len (lijst1) = 5 wordt niet gegeven.

2. Lijstbegrip gebruiken

Dit is de eenvoudige en aanbevolen manier om door een lijst in Python te bladeren.

Code:

 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;) 

Uitgang:

Hoe u door een lijst in Python kunt bladeren

Begrip:

Java-arraylist sorteren

We kunnen for-lussen gebruiken binnen een lijstbegrip. We gebruikten hetzelfde voor lussen die we in de bovenstaande voorbeelden gebruikten, maar dan in een lijst op één regel. Op deze manier kunnen we de lengte van de code verkleinen en is het begrijpen van lijsten een zeer subtiele en efficiënte manier om lussen in lijsten te plaatsen.

3. Met behulp van enumerate():

De enumerate-functie converteert de gegeven lijst naar een lijst met tupels. Een ander belangrijk feit over deze functie is dat deze de telling van de iteraties bijhoudt. Dit is een ingebouwde functie in Python.

Code:

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

Uitgang:

Hoe u door een lijst in Python kunt bladeren

4. Lambda-functie en map() gebruiken:

Dit zijn anonieme functies. Er is een functiekaart () in Python die een functie als argument kan accepteren, en deze roept de functie aan met elk element in de iterabele, en een nieuwe lijst met alle elementen uit de iterabele zal worden geretourneerd.

Code:

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

Uitgang:

Hoe u door een lijst in Python kunt bladeren

Begrip:

Het lambda num: num wordt samen met de lijst als invoer voor de kaartfunctie opgegeven. De functie neemt elk afzonderlijk element in de lijst, accepteert het en retourneert het vervolgens. De functie map () geeft de lijstelementen één voor één door aan de lambda-functie om de elementen terug te geven.

Wat als we multidimensionale lijsten willen herhalen?

Er is een ingebouwde module in Python die is ontworpen om bewerkingen uit te voeren op multidimensionale lijsten.

1. Om numpy te worden:

Controleer of Python en pip zijn geïnstalleerd door de cmd te openen via zoeken en de opdrachten te typen:

tostring java

Python-versie

Pip-versie

Als zowel Python als PIP in ons systeem aanwezig zijn, is het nu tijd om onze bibliotheek te installeren:

2. Open cmd vanuit het startmenu

3. Typ de opdracht

pip installeer numpy

Hoe u door een lijst in Python kunt bladeren

Alle bibliotheekpakketten, gegevens en subpakketten worden één voor één geïnstalleerd.

Code:

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

Uitgang:

Hoe u door een lijst in Python kunt bladeren

Begrip:

We hebben de numpy-module geïmporteerd. Met behulp van de arrange-methode hebben we een array met 9 elementen gemaakt. We hebben toegang gekregen tot de lijst door deze opnieuw vorm te geven naar 3 * 3 (rijen * kolommen) met behulp van de nieuwe vorm. Met behulp van de nditer-functie hebben we elk element in de lijst afgedrukt.