lte__ lte__ - 2 months ago 30
Python Question

mapping the append function to a list

I want to do the following elegantly. I have a list:

list1 = [[1,2],[3,1,4,7],[5],[7,8]]

I'd like to append the number 1 to each element of the list, so that I have

list1 = [[1,2,1],[3,1,4,7,1],[5,1],[7,8,1]]

I'm trying to map this via

map(list.append([1]), vectors)

but this returns the error
append() takes exactly one argument (0 given)
and if I just try
), I get
NameError: global name 'append' is not defined
. I guess I could do it with a loop, but this seems more elegant, is there a way to map this correctly?


Here is a several ways to implement what you want:

More readable and classic way

for el in list1:

List comprehension

list1 = [el + [1] for el in list1]


list1 = (el + [1] for el in list1)


list1 = map(lambda el: el + [1], list1)

What to use?

It depends on you own situation and may depends on execution speed optimizations, code readability, place of usage.

  • Map is a worst choice in case of readability and execution speed
  • for is a fastest and more plain way to do this
  • generators allows you do generate new list only when you really need this
  • List comprehension - one liner for classic for and it takes advantage when you need quickly filter the new list using if

i.e. if you need only add element to each item - for loop is a best choice to do this, but if you need add item only if item > 40, then you may consider to use List comprehension