Use the enumerate function in python, pythonenumerate
Enumerate () Description
- Enumerate () is a python built-in Function
- Enumerate indicates enumeration and enumeration in the dictionary.
- For an iterable/traversed object (such as a list or string), enumerate makes it an index sequence and obtains indexes and values at the same time.
- Enumerate is mostly used to get the count in the for loop.
Use enumerate ()
- If you want to traverse both the index and element in a list:
1 list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] 2 for index, item in enumerate (list): 3 print (index, item) 4 5 0 Monday 6 1 Tuesday 7 2 things 8 3 Thursday 9 Friday 10 5 Saturday 11 6 Sunday
- You can also specify the Starting sequence number enumerate (li, 1)
1 li = ["cell phone", "computer", 'mouse pad ', 'yacht'] 2 for k, v in enumerate (li, 1): 3 print (k, v) 4 5 1 mobile phone 6 2 computer 7 3 mouse pad 8 4 yacht