Python Basics: For I, Element In Enumerate(seq)..why/how Does This Work?
Solution 1:
enumerate
essentially turns each element of the input list into a list of tuples with the first element as the index and the element as the second. enumerate(['one', 'two', 'three'])
therefore turns into [(0, 'one'), (1, 'two'), (2, 'three')]
The bit just after the for
pretty much assigns i
to the first element and element
to the second for each tuple in the enumeration. So for example in the first iteration, i == 0
and element == 'one'
, and you just go through the other tuples to get the values for the other iterations.
Solution 2:
The actual definition of enumerate function is like this
enumerate(iterable[, start]) -> iterator forindex, value of iterable
Return an enumerate object. iterable must be another object that supports
iteration. The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
But the parameter seq if not defined will not return the desired output, rather it will throw an error like- NameError: name 'seq' is not defined.
Solution 3:
i am not sure what you want, to know enumerate or what's happening here in this . may this can help :
seq = ["one", "two", "three"]
for i range(3):
seq[i] = '%d: %s' % (i, seq[i])
>>> seq
['0: one', '1: two', '2: three']
actually , here "seq" is object of list-class. Each element in list reference to independent object of different class . when in above function ; first you get the reference of each list element's object by accessing "seq[i]", you create a new object using referenced object value (can belongs to other class), now u again referencing the "seq[i]" to new created object for each element .
Solution 4:
You are right. seq is not defined. Your snippet will not work. It will only work if seq has ben set to seq = ['one', 'two', 'three'] before. Just try it!
Post a Comment for "Python Basics: For I, Element In Enumerate(seq)..why/how Does This Work?"