Day 29: Python Enumerate


According to the Python documentation, Enumerate is a built-in function of Python. It allows us to loop over something and have an automatic counter. It returns an enumerate object.

Syntax:
enumerate(sequence, start=0)

sequence must be a sequence, an iterator, or some other object which supports iteration.
The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.

An example codes as below:

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))

# Output:
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

It returns a tuple as mentioned,(0, ‘Spring’).
Another example codes using for loop:

my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
    print(c, value)

# Output:
1 apple
2 banana
3 grapes
4 pear

The ‘start’ is an optional argument and default value is 0. You can format the print() statement to display the index and value in meaningful way.

Another exercise from DataCamp which I want to share the codes and output here:

# areas list
areas = [11.25, 18.0, 20.0, 10.75, 9.50]

# Change for loop to use enumerate() and update print()
for a, value in enumerate(areas,1) :
    print("room " + str(a) + ": " + str(value))

# Output:
room 1: 11.25
room 2: 18.0
room 3: 20.0
room 4: 10.75
room 5: 9.5

I noticed the ‘a, value’ sequence is not an matter here as the first value returns by enumerate() function is the index and follow by the value.

Remember how the tuple returns the output? (0, ‘Spring’).

Another interesting DataCamp’s exercise on enumerate() function as below:

Write a for loop that goes through each sublist of house and prints out the x is y sqm, where x is the name of the room and y is the area of the room.

# house list of lists
house = [["hallway", 11.25], 
         ["kitchen", 18.0], 
         ["living room", 20.0], 
         ["bedroom", 10.75], 
         ["bathroom", 9.50]]
         
# Build a for loop from scratch
for a, value in enumerate(house):
    print("the " + str(house[a][0]) + " is " + str(house[a][1]) + " sqm")

# Output:
the hallway is 11.25 sqm
the kitchen is 18.0 sqm
the living room is 20.0 sqm
the bedroom is 10.75 sqm
the bathroom is 9.5 sqm

# A normal loop returns same result as above:
for x in house:
    print("the " + str(x[0]) + " is " + str(x[1]) + " sqm")
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s