Python Forum

Full Version: Need to understand the way enumerate() function works
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Friends, I am a novice and trying to understand how the various python functions work. Please help me understand how enumerate() function works. I have tried some code by my own to get the concepts clear. If someone can explain how the function has worked after the change, it will be helpful

<<<< CODE START >>>>


>>> def printStuff(Stuff):
	"""First definition of the function"""
	for i,s in enumerate(Stuff):
		print("Album ", i," Rating is", s)

		
>>> album_ratings = [10.0, 8.5, 9.5]

>>> printStuff(album_ratings)
Album  0  Rating is 10.0
Album  1  Rating is 8.5
Album  2  Rating is 9.5


>>> def printStuff(Stuff):
	"""Second definition of the function"""
	for i,s in enumerate(Stuff):
		print("Album ", enumerate(Stuff)," Rating is", s)

		
>>> printStuff(album_ratings)
Album  <enumerate object at 0x0000016C807731B0>  Rating is 10.0
Album  <enumerate object at 0x0000016C807731B0>  Rating is 8.5
Album  <enumerate object at 0x0000016C807731B0>  Rating is 9.5
The enumate function expressed as generator looks like this:

def enum_gen(iterable, start=0, step=1)
    for element in iterable:
        yield (start, element) # <- Here the generator is paused till the next iteration
        start += step # increment the internal counter by step

gen = enum_gen([1,2,3,4]) # <- This creates the generator, no code execution
next(gen) # this is what the for-loop does implicit
# until a StopIteration has been raised.
# the Exception comes from the generator, when it has been finished with the for-loop
First function some changes.
Usually want a rating list to start at count at one,then can give 1 as argument.
def print_stuff(stuff):
    '''First definition of the function'''
    for rate_count,rating in enumerate(stuff, 1):
        print(f'Album {rate_count} Rate is {rating}')

album_ratings = [10.0, 8.5, 9.5]
print_stuff(album_ratings)
Output:
Album 1 Rate is 10.0 Album 2 Rate is 8.5 Album 3 Rate is 9.5

In function two in body of loop enumerate(Stuff).
So is only first element repeated 3 times,see 0x0000016C807731B0(object memory address) is same in each loop.
>>> album_ratings = [10.0, 8.5, 9.5]
>>> next(enumerate(album_ratings))
(0, 10.0)
>>> next(enumerate(album_ratings))
(0, 10.0)
>>> next(enumerate(album_ratings))
(0, 10.0)
So it really wrong use of enumerate().

Values are there if use list() to look at it,but then need a new loop to get theme out.
>>> album_ratings = [10.0, 8.5, 9.5]
>>> list(enumerate(album_ratings))
[(0, 10.0), (1, 8.5), (2, 9.5)]
>>> 
>>> for index,item in enumerate(album_ratings):
...     index,item
...     
(0, 10.0)
(1, 8.5)
(2, 9.5)