Python enumerate()

ItsMyCode |
The enumerate() in Python is a built-in function that adds a counter as a key to an iterable object ( list , tuple , etc.) and returns an enumerating object.
enumerate() Syntax
The syntax of enumerate() is:
**enumerate(iterable, start=0)**
enumerate() Parameters
The enumerate() function takes two parameters.
  • iterable – any object that supports iteration. E.g.:- list , tuple , etc.
  • start (optional) – the index value from which the counter needs to be started. If not specified, the default value is taken as 0
  • enumerate() Return Value
    The enumerate() method adds a counter as a key to an iterable object ( list , tuple , etc.) and returns an enumerating object.
    The enumerated object can then be used directly for loops or converted into lists and tuples using the list() and tuple() method.
    Example 1: How enumerate() method works in Python?
    # Python program to illustrate enumerate function
    
    fruits = ['apple', 'orange', 'grapes','watermelon']
    enumeratefruits = enumerate(fruits)
    
    # check the type of object
    print(type(enumeratefruits))
    
    # converting to list
    print(list(enumeratefruits))
    
    # changing the default from 0 to 5
    enumeratefruits = enumerate(fruits, 5)
    print(list(enumeratefruits))
    Output
    <class 'enumerate'>
    [(0, 'apple'), (1, 'orange'), (2, 'grapes'), (3, 'watermelon')]
    [(5, 'apple'), (6, 'orange'), (7, 'grapes'), (8, 'watermelon')]
    Example 2: Using Enumerate object in loops
    # Python program to illustrate enumerate function in loops
    
    lstitems = ["Ram","Processor","MotherBoard"]
    
    # printing the tuples in object directly
    for ele in enumerate(lstitems):
        print (ele)
    
    print('\n')
    
    # changing index and printing separately
    for count,ele in enumerate(lstitems,100):
        print (count,ele)
    
    print('\n')
    
    #getting desired output from tuple
    for count,ele in enumerate(lstitems):
        print(count, ele)
    Output
    (0, 'Ram')
    (1, 'Processor')
    (2, 'MotherBoard')
    
    100 Ram
    101 Processor
    102 MotherBoard
    
    0 Ram
    1 Processor
    2 MotherBoard
    The post Python enumerate() appeared first on ItsMyCode.

    24

    This website collects cookies to deliver better user experience

    Python enumerate()