- 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
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.
Iterating using the index isn’t recommended if we will iterate over the elements (as done in Method #1).
Method #3: Using while loop
Method #4: Using list comprehension (Possibly the most concrete way).
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.
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.