andio
andio

Reputation: 1778

Using lambda to create new list by altering/modifying old list

oldlist=['a','b','c']
print newlist=[(lambda x : x+x )(x) for x in oldlist ]
# Result: ['aa', 'bb', 'cc']

Now I want to have the output like this:

newlist=['1a','2b','3c']

Hopefully I want to do it using lambda like this:

idx=1
newlist=[(lambda x : str(idx)+x ; idx+=1)(x) for x in oldlist ]

But I'm not allowed to use multiline expression in lambda. So how do I increment idx inside that lambda?

Upvotes: 1

Views: 67

Answers (3)

Antwane
Antwane

Reputation: 22658

Why don't you simply use enumerate with standard python list definitions:

>>> oldlist = ['a','b','c']
>>> newlist = [str(idx + 1) + e for idx, e in enumerate(oldlist)]
>>> print(newlist)
['1a', '2b', '3c']

Upvotes: 0

falsetru
falsetru

Reputation: 369274

You don't need to use lambda at all.

Use enumerate:

>>> oldlist = ['a','b','c']
>>> enumerate(oldlist)
<enumerate object at 0x7f5e58a455f0>
>>> list(enumerate(oldlist))  # default start = 0
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> list(enumerate(oldlist, 1))  # explicitly specify `start`
[(1, 'a'), (2, 'b'), (3, 'c')]

>>> oldlist = ['a','b','c']
>>> [str(i) + x for i, x in enumerate(oldlist, 1)]
['1a', '2b', '3c']

Alternatively, you can use next with itertools.count iterator:

>>> import itertools
>>> it = itertools.count(1)  # yield 1, 2, 3, ... infinitely.
>>> next(it)
1
>>> next(it)
2

>>> import itertools
>>> it = itertools.count(1)
>>> [str(next(it)) + x for x in oldlist]
['1a', '2b', '3c']

Upvotes: 3

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

You cannot increment inside lambda, you will have to pass incremented value from outside (If you must use lambda, as lambda is not needed here as suggested by @falsetru). Use enumerate and pass index to lambda.

newlist=[(lambda idx, x : str(idx)+x)(idx, x) for (idx, x) in enumerate(oldlist, 1) ]

Upvotes: 1

Related Questions