Python Enumerate

Flag as Inappropriate

Please select the category that most closely reflects your concern about the presentation, so that we can review it and determine whether it violates our
Terms of Use or isn't appropriate for all viewers.

Submit

Like this presentation?

Embed this comment into your blog:

Comment URL:

No comments posted yet

Comments

1-10 of 34

Post a comment

Post

1-10 of 34

Sign In

Copyright @ 2018 Learntek. All Rights Reserved.
2
Python Enumerate :
python enumerate() is basically a python built in function. During certain situations where we deal with lot of iterators we also need to keep count of iterations, in these type of situations python built in function Enumerate comes handy. It helps to add counter to the iterable and returns an enumerate object.
The basic syntax :-
The enumerate() function takes two parameters namely :
iterable – It is a sequence, an iterator or objects which support iteration.
start – It is an optional parameter and enumerate starts to count if provided. By default, 0 is set if start parameter is not provided.
The returned enumerate object can be converted into list and tuple using list() and tuple() method.
Let us see some examples of enumerate() function.
enumerate(iterable, start=0)

Slide 3

Copyright @ 2018 Learntek. All Rights Reserved.
3
Example 1: The below example creates an enumerate object using enumerate() function. We can check the type of the object by using another built in function type(). We also convert the enumerate object to list by using list() function.
action_movies = [‘The world is not enough’, ‘Speed’, ‘Saving Private Ryan’] enumerateActionMovies = enumerate(action_movies) print(type(enumerateActionMovies)) # convert to list print(list(enumerateActionMovies))
# provide second parameter other than default value enumerateActionMovies = enumerate(action_movies, 10) print(list(enumerateActionMovies))
Output:
<class ‘enumerate’> [(0, ‘The world is not enough’), (1, ‘Speed’), (2, ‘Saving Private Ryan’)] [(10, ‘The world is not enough’), (11, ‘Speed’), (12, ‘Saving Private Ryan’)]

Slide 4

Copyright @ 2018 Learntek. All Rights Reserved.
4
Example 2:
Passing second parameter. In the below example we will print out the list of travel destination along with the count. Do note here second parameter is starting with 1.
my_travel_list = [‘London’, ‘New York’, ‘Singapore’, ‘Melbourne’] for c, value in enumerate(my_travel_list, 1): print(c, value)
Output:
# 1 London # 2 New York # 3 Singapore # 4 Melbourne