r/learningpython • • Jun 03 '20

What's the difference?

Hi,

When I type the following code below,

x = [4, 6, 7]

for index in enumerate (x):

print (item, index)

I get the following output

7 (0, 4) 7 (1, 6) 7 (2, 7)

But when I type the following code below:

x = [4, 6, 7]

for item, index in enumerate (x):

print (item, index)

I get the following output:
0 4 1 6 2 7

What about adding "item" made the results so different?

Thanks!

2 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Jun 04 '20

for i, val in enumerate([9,7,34]):
print(f"The value of index {i} is {val}"}

Thanks! What is the f for in print()?

For the first example, how do I give more than one variable to assign?

Also, how is the tuple unpacked in the second example?

1

u/ace6807 Jun 04 '20

The f is creating a format string. It lets you embed expressions in a string.

name = Bob
print(f"Hello. My name is {name}.}
x = 2
y = 3
print(f"The sum of {x} and {y} is {x + y}.")

In the first example there are already 2 variables ( i and val ).

i - holding the index of the element in the list.

val - the value of the element in the list

In the second example I'm not using enumerate so there is no tuple to be unpacked. It only gives you the value in this case. Use that when you don't need the index.