oursolutionarchitectoursolutionarchitect
  • Python Questions and Answers
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
    • Selected Reading
    • Q&A

    Python - Loop Lists


    Loop Through List Items

    You can traverse the items in a list with Python's for loop construct. The traversal can be done, using list as an iterator or with the help of index.

    Syntax

    Python list gives an iterator object. To iterate a list, use the for statement as follows −

    for obj in list:
       . . .
       . . .
    

    Example

    Take a look at the following example −

    lst = [25, 12, 10, -21, 10, 100]
    for num in lst:
       print (num, end = ' ')
    

    Output

    25 12 10 -21 10 100
    

    Loop Through List Items with Index

    To iterate through the items in a list, obtain the range object of integers "0" to "len-1". See the following example −

    Example

    lst = [25, 12, 10, -21, 10, 100]
    indices = range(len(lst))
    for i in indices:
       print ("lst[{}]: ".format(i), lst[i])
    

    Output

    lst[0]: 25
    lst[1]: 12
    lst[2]: 10
    lst[3]: -21
    lst[4]: 10
    lst[5]: 100