58

I have a list of lists, and would like to use list comprehension to apply a function to each element in the list of lists, but when I do this, I end up with one long list rather than my list of lists.

So, I have

x = [[1,2,3],[4,5,6],[7,8,9]]
[number+1 for group in x for number in group]
[2, 3, 4, 5, 6, 7, 8, 9, 10]

But I want to get

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

How do I go about doing this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jean-Luc
  • 3,563
  • 8
  • 40
  • 78

3 Answers3

85

Use this:

[[number+1 for number in group] for group in x]

Or use this if you know map:

[map(lambda x:x+1 ,group) for group in x]
Booster
  • 1,650
  • 13
  • 18
  • 6
    I realize the OP is using python2, but for future users seeing this that are using python3, map returns a *map object*, so you would have to do `[list(map(lambda x:x+1 ,group)) for group in x]` to get the same result. – SethMMorton Feb 02 '14 at 05:52
2

Starting from the structure of your data:

x = [[1,2,3],[4,5,6],[7,8,9]]

Every group is a triplet [a,b,c], so I consider for readability a solution like:

«take every group [a,b,c] from the list and provide me the list of [a+1,b+1,c+1] »

x_increased = [ [a+1,b+1,c+1] for [a,b,c] in x ]

dodo
  • 21
  • 2
-1
lista = [[i+3*(j-1) for i in range(1,4)] for j in range(1,4)]

print(lista)
# outputs [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
technogeek1995
  • 3,185
  • 2
  • 31
  • 52
  • 3
    Welcome to SO! When crafting an answer, it's important to include some explanation for what the code is doing to create a more robust answer. If you need additional help, check out [how to answer](https://stackoverflow.com/help/how-to-answer). – technogeek1995 Jul 24 '19 at 16:49