enumerate(): adds a counter to an iterable

enumerate(iterator,start) get enumerate object
iterator: Any iterator object or sequence of numbers
start: (optional) Starting number , default value is 0
Example of iterable objects are : List, tuple, dictionary , string We will use a list
my_list=['One','Two','Three','Four']
en=enumerate(my_list)
print(list(en))
Output
[(0, 'One'), (1, 'Two'), (2, 'Three'), (3, 'Four')]
Using index and value of a list.
my_list=['Alex','Ronald','John'] 
for i, my_name in enumerate(my_list): 
	print('Name #{}: {}'.format(i + 1, my_name))
Output
Name #1: Alex
Name #2: Ronald
Name #3: John

Using start option

We can set starting number to any value, by default starting is 0. We used a tuple()
my_list=('One','Two','Three','Four') 
en=enumerate(my_list,100) 
print(list(en))
Output
[(100, 'One'), (101, 'Two'), (102, 'Three'), (103, 'Four')]
Let us use enumerate() with one string
my_str='plus2net'
en=enumerate(my_str) 
print(list(en))
Output
[(0, 'p'), (1, 'l'), (2, 'u'), (3, 's'), (4, '2'), (5, 'n'), (6, 'e'), (7, 't')]

Example 1: Enumerating a List with a Custom Start Index

By default, enumerate() starts counting from 0, but we can specify a different starting index using the start parameter.

languages = ['Python', 'C++', 'Java', 'Ruby']
for index, language in enumerate(languages, 1):
    print(f"Language {index}: {language}")
Language 1: Python
Language 2: C++
Language 3: Java
Language 4: Ruby

Example 2: Enumerating a Tuple

The enumerate() function can also be used with tuples to access both index and value.

my_tuple = ('apple', 'banana', 'cherry')
for index, value in enumerate(my_tuple):
    print(f"Index {index}: {value}")
Index 0: apple
Index 1: banana
Index 2: cherry

Example 4: Enumerating a List of Tuples

When working with a list of tuples, enumerate() can be particularly useful to keep track of the index while unpacking the tuple elements.

students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]
for index, (name, score) in enumerate(students, 1):
    print(f"Student {index}: {name} scored {score}")
Student 1: Alice scored 85
Student 2: Bob scored 90
Student 3: Charlie scored 78

Example 5: Enumerating a Dictionary

While dictionaries are not sequences, they are iterable. Using enumerate() with dictionaries allows us to access the index along with the key-value pairs.

my_dict = {'a': 1, 'b': 2, 'c': 3}
for index, (key, value) in enumerate(my_dict.items()):
    print(f"Index {index}: Key = {key}, Value = {value}")
Index 0: Key = a, Value = 1
Index 1: Key = b, Value = 2
Index 2: Key = c, Value = 3
Dynamically create Checkbuttons using dictionary data with enumerate()

Use Case: Accessing and Displaying Indexed Data

Enumerating dictionaries is particularly useful when displaying data in an ordered way, such as creating an indexed list of user settings, storing configuration details, or managing key-value pairs with position tracking.

Best Practices

  • Use enumerate() when you need to keep track of an index while iterating.
  • For dictionary enumeration, use my_dict.items() to retrieve both keys and values.
  • Consider using start argument in enumerate() if a custom index starting value is required.
  • When working with large dictionaries, ensure efficient memory usage by avoiding unnecessary type conversions.

Checking data type

We will use type() to get the data type
my_list=['One','Two','Three','Four']
en=enumerate(my_list)
print(type(en))   # <class 'enumerate'>
All Built in Functions in Python interator generator float()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer