Issue
I have a question about strings. I thought that this code:
for n in 'banana':
print(n)
would return this:
0 1 2 3 4 5
But, of course, it doesn't. It returns the value at each position in the string, not the position number. In order for me to understand this better, I thought it might help to write the simplest possible program to achieve the output I thought I'd get:
count = 0
for n in 'banana':
print(count)
count += 1
This works, but surely there's a more direct way to access the position number that the current iteration is looking at? Can't see any methods that would achieve this directly though.
Solution
These are all equivalent:
i = 0
for n in 'banana':
print(i)
i += 1
for i, w in enumerate('banana'):
print(i)
for i in range(len('banana')):
print(i)
print(*range(len('banana')), sep='\n')
Answered By - Riccardo Bucco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.