'append or extend using Lambda in Python

I want to do this:

def my_func(x):
    x.extend('\n')
    return x

var1 = [['a', 'b'], ['c', 'd']]

for item in var1:
    var2 = my_func(item)
    print(var2)
>>>
['a', 'b', '\n']
['c', 'd', '\n']

using Lambda function. When I try

var1 = [['a', 'b'], ['c', 'd']]
var_x = list(map(lambda x: x.extend('\n'), var1))
>>>
[None, None]

How to write it then???



Solution 1:[1]

extend mutates the list in-place and returns None. You should try to use something like:

x + ['\n']

instead of:

x.extend('\n')

Solution 2:[2]

I do not understand the why, but here is the how:

var1 = [['a', 'b'], ['c', 'd']]

f = lambda x: list(map(lambda y: y.extend('\n'), x))

var2 = f(var1)
print(var1)  # [['a', 'b', '\n'], ['c', 'd', '\n']]

Or , if you want to keep the for-loop:

var1 = [['a', 'b'], ['c', 'd']]

f = lambda x: x + ['\n']

for sublist in var1:
  var2 = f(sublist)
  print(var2)

# ['a', 'b', '\n']
# ['c', 'd', '\n']

Solution 3:[3]

If you want to extend a list within a lambda (one valid case for this would be if you have several lists and want to reduce them to one cumulative list), you could use the following lambda:

lambda accum, chunk: (accum.extend(chunk), accum)[1]

This would be creating a temporary tuple of (None, accum), but since list.extend is a mutating operation you'd actually get what you need.

In your particular case, the code would be like this:

var1 = [['a', 'b'], ['c', 'd']]
var_x = list(map(lambda x: (x.extend('\n'), x)[1], var1))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ma0
Solution 2
Solution 3 Semisonic