Why can't I change or reassign the values of variables in lists using a for loop (python)?

后端 未结 3 1300
無奈伤痛
無奈伤痛 2020-12-21 23:18

If I have a list of numbers, and I want to increment them using a for loop, why isn\'t this working:

>>> list=[1,2,3,4,5]
>>> for num in l         


        
3条回答
  •  萌比男神i
    2020-12-21 23:39

    You can achieve this by indexing the array.

    >>> list=[1,2,3,4,5]
    >>> for i in range(len(list)): 
    ...  list[i]=list[i]+1
    

    This will circumvent the referencing issue Lattyware spoke of.

提交回复
热议问题