abh
abh

Reputation: 51

Adding to a list of list of integers

I have a list x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]. I want to add y = 400, to each of the elements in the list. The output should be z = [3273, 5721, 5821], 3188, 5571, 5671], [3188, 5571, 5671]]

I tried by using

def add(x,y): 
addlists=[(x[i] + y) for i in range(len(x))]    
return addlists
z = add(x,y) 

But that didn't work.

I've also tried

def add(x,y):
addlists = [(x[i] + [y]) for i in range(len(x))]
    return addlists
z = add(x,y) 

But that returns z = [[2873, 5321, 5421] + 400, [2788, 5171, 5271] + 400, [2788, 5171, 5271]+ 400]

Upvotes: 3

Views: 73

Answers (2)

s3dev
s3dev

Reputation: 9681

As another approach, if you wanted to go as far as using numpy you can use the following.

Depending on the size of your dataset, this approach might provide some efficiency gains over using nested loops, as numpy employs a method known as 'broadcasting' to apply a given operation to each value in the array, rather than ‘conventional looping’.

Additionally, this method scales well as it’s flexible to the shape of the lists.

For example:

import numpy as np

x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]
a = np.array(x)

a + 400

Output:

array([[3273, 5721, 5821],
       [3188, 5571, 5671],
       [3188, 5571, 5671]])

Update:

This update addresses the following comment question:

... is it possible to add to only the 2 last elements in each of the list in the array ...

Yes, absolutely - use slicing. Here is a link to a simple slicing tutorial.

For example:

a[:,-2:] += 400

Output:

array([[2873, 5721, 5821],
       [2788, 5571, 5671],
       [2788, 5571, 5671]])

Explanation:

a[:,-2:] += 400
^ ^  ^    ^
| |  |    |
| |  |    \ Apply the addition in place.
| |  |
| |  \ Apply the addition to only the last 2 elements.
| |
| \ Apply the addition to all arrays.
|
\ Array to be sliced

Upvotes: 2

Vin
Vin

Reputation: 1035

Try this:

x = [[2873, 5321, 5421], [2788, 5171, 5271], [2788, 5171, 5271]]

y = 400

z = [[y + each for each in eachlist] for eachlist in x]
print (z)
# result: 
[[3273, 5721, 5821], [3188, 5571, 5671], [3188, 5571, 5671]]

Upvotes: 0

Related Questions