13/18 - Modifying each element in a list in a function


#1

Q:why i have to use range?

n = [3, 5, 7]
def double_list(x):
for number in x:
number=number*2
return x
print double_list(n)


#2

You don’t have to use the range unless it is the indexed values you are interested in manipulating.

>>> foo = ['bar','bar','bar','bar','bar']
>>> for x in range(len(foo)):
	foo[x] = 'foo'

	
>>> foo
['foo', 'foo', 'foo', 'foo', 'foo']
>>> for x in foo:
	foo[x] = 'bar'

	

Traceback (most recent call last):
  File "<pyshell#38>", line 2, in <module>
    foo[x] = 'bar'
TypeError: list indices must be integers, not str
>>> 

People think they can get around this by assigning to the variable, but soon discover that nothing happens…

>>> for x in foo:
	x = 'bar'

	
>>> foo
['foo', 'foo', 'foo', 'foo', 'foo']
>>> 

Changing the value of the iterator variable has no effect. It gets obliterated with the next iteration.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.