Python Forum
Absolutely new to python - basic advise needed - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Absolutely new to python - basic advise needed (/thread-27598.html)



Absolutely new to python - basic advise needed - mariolucas75 - Jun-12-2020

Dear community,

I am absolutely new to Python but like to learn it.
Could you pls help to understand following code ( I dont understand the bold portion of the code):

# enumerate function in loops 
l1 = ["eat","sleep","repeat"] 
  
# printing the tuples in object directly 
for ele in enumerate(l1): 
    print (ele) 

# changing index and printing separately
# I don't understand next part
for count,ele in enumerate(l1,100): 
    print (count,ele) 
So i dont understand what does count,ele is ? Shouldn't it be one variable after for? what is the comma in between count and ele? And why it removes parentheses in output?


RE: Absolutely new to python - basic advise needed - buran - Jun-12-2020

enumearte(ietrable, start) takes 2 arguments - iterable and optional start argument.
In your case these is l1 list and start is 100.
enumerate will return 2-element tuple (index, element).
this tuple is unpacked into two variables - count and ele. so in each iteration count takes the value of index and ele is the element

the docs: https://docs.python.org/3/library/functions.html#enumerate


RE: Absolutely new to python - basic advise needed - Yoriz - Jun-12-2020

To add to buran's reply

Wording taken direct from the python docs Wrote:
d = 1, 2, 3
The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple.
The reverse operation is also possible:

x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignments are really just a combination of tuple packing and sequence unpacking.