CutePoison
CutePoison

Reputation: 5355

Create a list of each element after an iteration of list comprehension

I have a list y=[[1,1,1],[2,2,2]] and say (for the illustration of the problem) that I want to add 1 to each element, but still keeping it in the same format, ending up with yp1=[[2,2,2],[3,3,3]].

If I do

yp1 = [val+1 for lists in [num for num in y] for val in lists]

I just got yp1 as a flattened list.

Upvotes: 0

Views: 36

Answers (1)

bigbounty
bigbounty

Reputation: 17368

Understanding of list comprehension is needed here and it also depends on where you put the square brackets

y=[[1,1,1],[2,2,2]]

yb1=[[j+1 for j in i] for i in y]

print(yb1)

Output:

[[2, 2, 2], [3, 3, 3]]

Upvotes: 2

Related Questions