I'm taking a course called the return value of a function using a tuple. I'm posting a question because I don't understand something.
names = ["Cheolsoo", "Younghee", "Youngsoo"]
for i in range(len(names)):
name = names[i]
print('{} number: {}'.format(i + 1, name))
for i, name in enumerate(names):
print('{} number: {}'.format(i + 1, name))
As you can see, it's a for loop statement. The second code says that you can accept both the order and the value using enumerate, but where did the 'name' (the 9th line) after i+1 come from? I didn't specify a variable like name = names[i] like the first code, but I couldn't understand it even if I turned it around a few times.
The second question.
list = [1, 2, 3, 4, 5]
for i, v in enumerate(list):
print('{}th value: {}'.format(i, v))
list = [1, 2, 3, 4, 5]
for a in enumerate(list):
print('{}th value: {}'.format(a[0], a[1]))
Yes, as you can see, they have the same output. I don't know how a[0], a[1] is used here.
Thank you.
python3 tuple for loops
The name of the first question is specified as the variable to be interleaved in the for statement. You'll see if you look closely again.
In the second question, a is a variable that receives an enumerated index number and an element in the list, that is, i, v
in the for statement right above it. a = (i, v)
and a[0] => i
and a[1] => v
.
© 2024 OneMinuteCode. All rights reserved.