user1483363
user1483363

Reputation:

Altering list while iterating

Python noob here. I have a list of numbers represented as strings. Single digit numbers are represented with a zero and I'm trying to get rid of the zeroes. For instance, ['01', '21', '03'] should be ['1', '21', '3'].

My current solution seems a bit clumsy:

for item in list:  
    if item[0] == '0':     
        list[list.index(item)] = item[1]

I'm wondering why this doesn't work:

for item in list:  
    if item[0] == '0':  
        item = item[1]

Upvotes: 1

Views: 133

Answers (4)

Ned Batchelder
Ned Batchelder

Reputation: 376022

To mutate the list:

for i, item in enumerate(mylist):  
    if item.startswith('0'):     
        mylist[i] = item[1:]

Better is probably just to create a new list:

new_list = [x.lstrip('0') for x in mylist]

Your code doesn't work because assigning to item merely gives the name item a new value, it doesn't do anything to the old value of item.

Upvotes: 3

dkamins
dkamins

Reputation: 21948

The code "item" is a variable that contains the value of the item as you iterate through the list. It has no reference to the list itself.

Your first solution is very slow because it will have to search the list for each item to find the index.

See other answers for examples of how to accomplish what you want.

Upvotes: -1

Blender
Blender

Reputation: 298532

You could try stripping the zero:

>>> map(lambda x: x.lstrip('0'), ['001', '002', '030'])
['1', '2', '30']

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799450

Rebinding the iterating name does not mutate the list.

Also:

>>> [str(int(x, 10)) for x in ['01', '21', '03']]
['1', '21', '3']

Upvotes: 4

Related Questions