In this article, we will learn about iterating/traversing over a list in Python 3.x. Or earlier.
A list is an ordered sequence of elements. It is a non-scalar data structure and mutable in nature. A list can contain distinct data types in contrast to arrays storing elements belonging to the same data types.
Method 1 − Using iterable without index
Example
list_inp = ['t','u','t','o','r','i','a','l','s','p','o','i','n','t'] # Iterate over the list for value in list_inp: print(value, end='')
Method 2 − Using general way via index
Example
list_inp = ['t','u','t','o','r','i','a','l','s','p','o','i','n','t'] # Iterate over the list for value in range(0,len(list_inp)): print(list_inp[value], end='')
Method 3 − Using the enumerate type
Example
list_inp = ['t','u','t','o','r','i','a','l','s','p','o','i','n','t'] # Iterate over the list for value,char in enumerate(list_inp): print(char, end='')
Method 4 − Using negative indexes
Example
list_inp = ['t','u','t','o','r','i','a','l','s','p','o','i','n','t'] # Iterate over the list for value in range(-len(list_inp),0): print(list_inp[value], end='')
All the above four methods yeilds the output displayed below.
Output
tutorialspoint
Method 5 − Using sliced lists
Example
list_inp = ['t','u','t','o','r','i','a','l','s','p','o','i','n','t'] # Iterate over the list for value in range(1,len(list_inp)): print(list_inp[value-1:value], end='') print(list_inp[-1:])
Output
['t']['u']['t']['o']['r']['i']['a']['l']['s']['p']['o']['i']['n']['t']
Conclusion
In this article, we learnt about iteration/traversal over a list data type. Also, we learnt about various implementation techniques.