Python Forum
Need to understand the way enumerate() function works
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need to understand the way enumerate() function works
#3
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)
Reply


Messages In This Thread
RE: Need to understand the way enumerate() function works - by snippsat - Sep-16-2018, 08:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  problem in using enumerate akbarza 4 840 Oct-11-2023, 10:55 AM
Last Post: perfringo
  The use of enumerate Frankduc 3 1,739 Jan-31-2022, 09:40 PM
Last Post: deanhystad
  Don't Understand Recursive Function muzikman 9 3,773 Dec-03-2020, 05:10 PM
Last Post: muzikman
  Function throws error but then works? Milfredo 10 3,855 Sep-12-2020, 05:16 AM
Last Post: Milfredo
  Trying to understand how import works in python patrick99e99 3 3,922 Jun-12-2018, 04:48 AM
Last Post: patrick99e99
  Don't understand why this quicksort code works lupoalberto 6 4,063 Mar-27-2018, 10:01 AM
Last Post: lupoalberto
  i don't understand how to use a variable outside of a function? Rius2 6 5,369 Oct-04-2017, 06:31 PM
Last Post: wavic
  understand function hermann 3 3,527 Sep-06-2017, 10:44 AM
Last Post: hermann
  Can't understand the output of this recursion function bigmit37 5 4,025 Apr-04-2017, 11:15 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020