I am studying the Learn Python The Hard Way PDF. On page 82 i come across this question.
- Could you have avoided that for-loop entirely on line 23 and just assigned range(0,6) directly to elements?
Given the code:
# we can also build lists, first start with an empty one
elements = []
# then use the range function to do 0 to 20 counts
for i in range(0, 6):
print "Adding %d to the list." % i # line 23
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was: %d" % i
It seems this is not possible unless i use the map function? Am i correct?
In python 2.x,
rangereturns a list. In 3.x, it returns an iterable range object. You can always uselist(range(...))to get a list.However,
for x in ydoes not requireyto be a list, just an iterable (such asxrange(2.x only),range,list,str, …)