- List is like arrays in other languages, with the extra advantage of being dynamic in size. In Python, the list may be a sort of container in Data Structures, which is used to store multiple data at the same time. Unlike Sets, lists in Python are ordered and have a definite count.
- There are multiple ways to iterate over a list in Python. Let’s see all the various ways to iterate over a list in Python, and performance comparison between them.
Method #1: Using For loop
Output
Method #2: For loop and range ()
In case we would like to use the traditional for loop which iterates from number x to number y.
Output
Iterating using the index isn’t recommended if we will iterate over the elements (as done in Method #1).
Method #3: Using while loop
Output
Method #4: Using list comprehension (Possibly the most concrete way).
Output
Method #5: Using enumerate ()
If we would like to convert the list into an iterable list of tuples (or get the index supported a condition check, for example in linear search you would possibly need to save the index of minimum element), you’ll use the enumerate() function.
Output
Note: Even method #2 is used to find the index, but method #1 can’t (Unless an additional variable is incremented every iteration) and method #5 gives a concise representation of this indexing.