AlanK
AlanK

Reputation: 9853

Iterator over list and change values

I'm trying to loop over a list of variables and make changes to them if required. Can anyone help fix this problem ?. When I print the second time the list is unchanged. I am expecting b and c to be {'lol'} {'test'} respectively. I am trying to do this, without creating a new list for the values but instead modifying the original variables.

a = 'a,b'
b = 'lol'
c = 'Test'
d = None

print a, b, c, d

f = lambda x: '{' + x + '}' if ',' not in x else x

for i in [a, b, c, d]:
    if i:
        i = f(i)

print a, b, c, d

Update:

def do_work(self, args):
    if args.a:
        if ',' not in args.a:
            args.a = '{' + args.a + '}'

    if args.b:
        if ',' not in args.b:
            args.b = '{' + args.b + '}'

    self.do_more_work(args)

Upvotes: 1

Views: 72

Answers (2)

Netwave
Netwave

Reputation: 42796

mapyour lambda function, map iterates over a list and applys a function for each element generating a NEW list:

a = 'a,b'
b = 'lol'
c = 'Test'
d = None

print(a, b, c, d)

f = lambda x: '{' + x + '}' if x and ',' not in x else x

my_list = [a, b, c, d]
my_list = map(f, my_list)

print (my_list)

Edit

In case you need the original values to be changed (as commented) you can just unpack them:

a, b, c, d = my_list = map(f, my_list)
print(my_list)
print(a)
print(b)
print(c)
print(d)

['a,b', '{lol}', '{Test}', None]
a,b
{lol}
{Test}

Upvotes: 3

Kasravnd
Kasravnd

Reputation: 107357

You didn't applied any change on your list.Actually in following line :

i = f(i)

i is just a throw away variable and doesn't point to your list items. And by reassigning it you just changed it for a moment till next iteration.

If you want to change the list items you need to access them by indexing, you can put the list in variable and loop over your list object then change the items by indexing. For that aim you can use enumerate like following :

a = 'a,b'
b = 'lol'
c = 'Test'
d = None

print(a, b, c, d)

f = lambda x: '{' + x + '}' if ',' not in x else x

my_list = [a, b, c, d]
for i,j in enumerate(my_list):
    if j:
        my_list[i] = f(j)

print (my_list)

Or as a more pythonic way you can use a list comprehension:

my_list = ([f(i) if i else i for i in my_list])

Upvotes: 2

Related Questions