Home > OS >  Removing the first element from all the sub-list in a nested list
Removing the first element from all the sub-list in a nested list

Time:07-08

I have a list of lists such that

a = [["append",5],["insert",7],["print",9,10]]

How can I remove the first value from each sublist within the list using map and lambda function?

This is my code

m =  map(lambda x : x.remove(x[0]), a)

And my output for list(m) is [None, None, None]

Can anybody please help me understand why this is happening and how can the code be corrected? Thanks!!!

CodePudding user response:

If you really want to do the map way, here is the working version:

m = list(map(lambda x: x[1:], a)) 

# or even better just use List Comp.

m1 = [x[1:] for x in a]

assert m == m1  

>>> m
[[5], [7], [9, 10]]

CodePudding user response:

Do you want to modify the existing lists or create new ones? Daniel Hao already covered creating new ones, so I'll cover modifying the existing ones.

You're getting Nones because in Python, mutator methods return None, and list.remove() is one such mutator method. For more info, see Why does append() always return None in Python?

The better solution is to not use map or lambda at all, because you'd be using them primarily for side-effects, which is bad, the same way that using a list comprehension for side-effects is bad. Just use a plain for-loop:

for sublist in a:
    del sublist[0]

Also note that I'm using del here. Using remove() as you are is redundant: instead of simply saying, "delete the first element", you're saying "get the first element then find the first occurrence and remove it".

CodePudding user response:

Here a functional approach to slice the items of each (sub)list.

Sometimes it is more the effort than the undertaking, see wjandrea's answer.

from operator import itemgetter

a = [["append",5],["insert",7],["print",9,10]]


print(list(map(itemgetter(slice(1, None)), a)))

Here a dirty hack to fix the behavior of the approach in the question:

print(list(map(lambda x: (x.pop(0), x)[1], a)))

Also remove can be used instead pop.

Remember that also the original object will be affected by such operations!

  • Related