1

Let's say I have a list, mylist, and I define it to be [1, 2, 3, 4, 5]. How is there a simple way to double every element of the list from within a for loop?

I know you could do something like:

for i in range(len(mylist)):
    mylist[i] *= 2

I also know that you could make a list comprehension:

mylist = [2*i for i in range(1, 6)

But is there a way to do it like this?

for num in mylist:
   #code goes here

I tried doing something like:

for num in mylist:
    num *= 2

but num is a local variable, so this doesn't modify mylist, just num. Does anyone know a good way to do this?

paper man
  • 488
  • 5
  • 19

3 Answers3

4

The usual way to do this is with a list comprehension, iterating directly over the list items, not indirectly via an index.

mylist = [1, 2, 3, 4, 5]
mylist = [2 * num for num in mylist]
print(mylist)

output

[2, 4, 6, 8, 10]

That replaces mylist with a new list object. That's generally ok, but sometimes you want to modify the existing object, eg when other objects have a reference to mylist. You can do that with a slice assignment.

mylist[:] = [2 * num for num in mylist]
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
1

It's not really possible since you shouldn't try to change a list while looping through it in that way. I would stick with your other two ways of manipulating the list

L.Rengel
  • 3
  • 3
  • It's ok to mutate a list you're iterating over, as long as you don't add or remove items. But even then, it's _possible_ to alter the number of items in the list if you're careful not to upset the indices of the items you haven't visited yet. Thus you can safely remove items from a list if you iterate over it in reverse. – PM 2Ring Oct 21 '17 at 13:35
1

Using an explicit for loop. Use enumerate while iterating and assign a new value to each item.

mylist = [1, 2, 3, 4, 5]
for i, n in enumerate(mylist):
    mylist[i] = n * 2

Just be careful - don't change the number of items in a list: Remove items from a list while iterating

wwii
  • 23,232
  • 7
  • 37
  • 77