enamul17
enamul17

Reputation: 159

Squaring particular elements of a list in Python

I have an input list as follows:

input =[[7.842, 2], 
       [4.6861, 4], 
       [9.128, 5]]

I want to square the second attribute of each row:

Output =[[7.842, 4], 
        [4.6861, 16], 
        [9.128, 25]]

How can I achieve that?

Upvotes: 0

Views: 52

Answers (2)

crissal
crissal

Reputation: 2647

The non-numpy version of this is:

>>> output_list = [[x[0], x[1] ** 2] for x in input_list]
[[7.842, 4], [4.6861, 16], [9.128, 25]]

Upvotes: 0

meTchaikovsky
meTchaikovsky

Reputation: 7666

Just try this, this will modify the array in place

test = np.array([[7.842, 2], 
       [4.6861, 4], 
       [9.128, 5]])

test[:,1] **= 2

Upvotes: 2

Related Questions