Reputation: 23
I'm curious as to why the comma can be added at the end of len(list) to refer to the last item in the list. Can anyone explain this? Does it work only in list? How about the other items in the list - Can I access by using len(list) as well?
list=[10,20,30,40,50,60]
for num in len(list),:
print(num,end=" ")
Output num is 6.
Upvotes: 0
Views: 196
Reputation: 133544
for num in len(nums),:
Is the equivalent of:
>>> nums = [10,20,30,40,50,60]
>>> for num in (len(nums), ):
... print(num)
...
6
Where (len(nums), )
is a one-tuple, a tuple with 1 single element.
The reason for this notation is because if I do
(len(nums))
without the ending ,
(comma) then Python decides that is just the same as len(nums)
and not a tuple at all, since we need the ability to use brackets for many things eg. for operations like
(1 + 2) * 3
So we have the ending comma to distinguish a tuple
With lists this is not necessary and we can simply write something like [len(nums)]
Upvotes: 2
Reputation: 4471
len(list)
returns a single integer, corresponding to the number of elements in your list list
(which, as an aside, is poorly named as you should avoid using built-in names for your variables). The comma in for num in len(list),
turns it into a one-tuple, meaning that the for loop can iterate one item, which you can see by running in the interactive interpreter:
len(list),
Output:
(6,)
Your for
loop, as you indicate, will print: 6
, which is the length of list
. It does not access the last element of list
, which is 60
.
This for
loop is unusual usage of this syntax, as it's obvious that there will only be a single element and no need to iterate.
Upvotes: 2