-3
A = [[1,2,3],[4,5,6]]

def addOne(a): 
    return a+1

addOne(A) doesn't work, obviously because I don't want A+1,

I want to get [[[2,3,4]],[5,6,7]]

[addone(x) for x in y for y in A] doesn't work either, I think list comprehensions doesn't work that way.

note, addOne is just a placeholder for a more complicated function

Mohammad Athar
  • 1,953
  • 1
  • 15
  • 31

1 Answers1

0
>>> nums = [[1, 2, 3], [4, 5, 6]]
>>> def add_one(a):
...     return a + 1
... 
>>> [list(map(add_one, sublist)) for sublist in nums]
[[2, 3, 4], [5, 6, 7]]
>>> [[add_one(num) for num in sublist] for sublist in nums]
[[2, 3, 4], [5, 6, 7]]
G_M
  • 3,342
  • 1
  • 9
  • 23
  • or just: [x+1 for x in A] – Mitch Wheat Feb 15 '18 at 00:55
  • 1
    @MitchWheat Maybe... but OP might just be using the "add_one" function as a placeholder to put a different function in later. – G_M Feb 15 '18 at 00:56
  • True................ – Mitch Wheat Feb 15 '18 at 00:57
  • @MitchWheat the duplicate you linked to doesn't really apply as per OPs latest edit: "note, addOne is just a placeholder for a more complicated function" – G_M Feb 15 '18 at 01:12
  • I can't help it if the poster chnages question! It's completely different.! – Mitch Wheat Feb 15 '18 at 01:14
  • @MitchWheat Yes, I see the examples have now changed from 1D to 2D but the question/title has always been the same: "is there any cleaner way to apply function to list". The duplicate you linked to does not apply a function to a list. – G_M Feb 15 '18 at 01:42