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
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')]
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):
Language 1: Python
Language 2: C++
Language 3: Java
Language 4: Ruby
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
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
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()
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.
my_list=['One','Two','Three','Four']
en=enumerate(my_list)
print(type(en)) # <class 'enumerate'>
All Built in Functions in Python interator generator
float()