Menu
List is equivalent to arrays in other languages, with the extra benefit of being dynamic in size. In Python, list is a type of container in Data Structures, which is used to store multiple data at the same time. Unlike Sets, the list in Python are ordered and have a definite count.
How can the answer be improved?
There are multiple ways to iterate over a list in Python. Let’s see all different ways to iterate over a list in Python, and a performance comparison between them.
Method #1: Using For loop
list = [ 1 , 3 , 5 , 7 , 9 ] # Using for loop print (i) |
Output:
Method #2: For loop and range()
![Iterating Over Dict Iterating Over Dict](/uploads/1/2/5/6/125624238/272855503.png)
In case we want to use the traditional for loop which iterates from number x to number y.
list = [ 1 , 3 , 5 , 7 , 9 ] # getting length of list # same as 'for i in range(len(list))' print ( list [i]) |
Output:
Iteratiner the the index is not recommended if we can iterate over the elements(as done in Method #1).
Method #3: Using while loop
Method #3: Using while loop
list = [ 1 , 3 , 5 , 7 , 9 ] # Getting length of list i = 0 # Iterating using while loop print ( list [i]) |
Output:
Method #4: Using list comprehension (Possibly the most concrete way).
list = [ 1 , 3 , 5 , 7 , 9 ] # Using list comprehension |
Output:
Method #5: Using enumerate()
If we want to convert the list into an iterable list of tuples (or get the index based on a condition check, for example in linear search you might need to save the index of minimum element), you can use the enumerate() function.
list = [ 1 , 3 , 5 , 7 , 9 ] # Using enumerate() print (i, ',' ,val) |
Output:
Note: Even method #2 can be used to find the index, but method #1 can’t (Unless an extra variable is incremented every iteration) and method #5 gives a concise representation of this indexing.
Method #6: Using Numpy
Method #6: Using Numpy
For very large n-dimensional lists (for example an image array), it is sometimes better to use an external library such as numpy.
# iterating over array # arrange method # and 4 columns for x in geek.nditer(a): |
Output:
We can use
np.ndenumerate()
to mimic the behaviour of enumerate. The extra power of numpy comes from the fact that we can even control the way to visit the elements (Fortran order rather than C order, say :)) but the one caveat is that the np.nditer
treats the array as read-only by default, so one must pass extra flags such as op_flags=[‘readwrite’]
for it to be able to modify elements.Recommended Posts:
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the 'Improve Article' button below.
From a discussion with Martijn Pieters at stackoverflow
This is meant as a comment, posted as an answer because it is too big for the comment system. Answering to Martijn Pieters:
PauloScardine: but now you are inserting a value lookup each iteration. That's not more efficient. And in this specific case, you'd have to call
vars(MyClass)
too, or do an extra attribute lookup with MyClass.__dict__
Probably the difference is marginal, but it is always good to profile before claiming some code is more efficient than other, so here we go:
Curiously:
Just a matter of taste then?
[update]
Forgot to call
foo.__dict__.items()
:Does it holds true for larger dicts?
[update]
Another error spotted - should be iterating over
Foo
, not foo
:Conclusion: after a certain size the call to
dict.items()
starts to pay off, but for the average use case I prefer the first style (iterating over the keys and making a dict lookup) instead of using dict.items()
. Mandatory quote from Knut: 'premature optimization is the root of all evil'.[and another update]
Now this is strange; Am I missing something?
Why the hell does it make any difference if Foo is instantiated or not?
[and another update]
Keeping the setup code outside of the loop yields more consistency:
Looks like dictionary lookup is way more expensive in python 3.4.