Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Tuples Multiple Return Values

Youssef Moustahib
Youssef Moustahib
7,779 Points

2 part question !

So in this video Kenneth taught us about enumerate. It goes through an iterable and gives us a tuple of the thing in the iterable and its index.

Why is when when Kenneth wrapped it into a list it printed properly

[(0, 'a'), (1, 'b'), (2, 's')]

But when I tried this is gave me a completely different answer:

<enumerate object at 0x7f27e0c196c0>    

My second question is, does enumerate belong to a tuples? Seeing as though it produces tuples? I understand how to use it but a little more explanation would help out a lot.


1 Answer

Viraj Deshaval
Viraj Deshaval
4,874 Points

What enumerate does is it add counter start with index 0 to the iterable i.e. string or list.

So when you did below:

<enumerate object at 0x7f27e0c196c0>

this created an enumerate object by adding the counter to the string literal 'abc'. We can then use this object to loop through either by using for loops or we can create list of tuples as Kenneth created.

>>> obj1 = enumerate('abc')                                                                                                    
>>> obj1                                                                                                                       
<enumerate object at 0x7ff22547b678>                                                                                           
>>> for count,str in obj1:                                                                                                     
...     print("String {}: {}".format(count, str))                                                                              
String 0: a                                                                                                                    
String 1: b                                                                                                                    
String 2: c

So this way we can loop through or make a list of tuples and use it as per our requirement.