stack aayush
stack aayush

Reputation: 33

How to add value to particular part of python list?

NOTE: My need isn't this e.g. List[2:4] = 5

Suppose my List=[1,2,3,4,5,6]

I want to add 5 from index 2 to 4.

So the resultant List would be like List=[1,2,8,9,10,6]

If I have 2d array List=[[1,2,3],[4,5,6]] and want to add 5 to col 1 List=[[6,2,3],[9,5,6]]then what would be the code?

Upvotes: 1

Views: 978

Answers (4)

stack aayush
stack aayush

Reputation: 33

One solution uses NumPy but my implementation is on an in-built list and other solutions are copying unnecessary elements.

So here I found the manual way to do it.

List = [[1,2,3,4,5],[6,7,8,9,10]]
# for horizontal update
colToUpdate = 2
for r in range(0,2):
    A[r][colToUpdate] += add

# for vertical update
rowToUpdate = 1
for c in range(2,5):
    A[rowToUpdate][c] += add

Upvotes: 0

Red
Red

Reputation: 27547

Numpy arrays can handle such slice operations:

import numpy as np

List = np.array([1, 2, 3, 4, 5, 6])
List[2:5] += 5
print(List)

Numpy will really come in handy for you if you have many of such tasks to do in your code. However, if it's just a one time thing in your code, you can do:

List = [1, 2, 3, 4, 5, 6]
for i in range(2, 5):
    List[i] += 5
print(List)

Output:

[1, 2, 8, 9, 10, 6]

EDIT

Addressing your edit, you can also use numpy arrays like so:

import numpy as np

List = np.array([[1, 2, 3], [4, 5, 6]])
List[0] += 5
print(List)

Or using a loop:

List = [[1, 2, 3], [4, 5, 6]]
for i in range(len(List[0])):
    List[0][i] += 5
print(List)

Output:

[[6, 7, 8], [4, 5, 6]]

Upvotes: 1

Max Shouman
Max Shouman

Reputation: 1331

This can be easily done through list comprehension.

The following function takes a 2D array 2d, a position index i and a value v, and adds v to the i-th element of each array.

def add_value(2d, i, v):
   return [array[:i] + [array[i]+v] + array[i+1:] for array in 2d]

So, calling the function on the list in your example:

my_list = [[1,2,3],[4,5,6]]
add_value(my_list,0,5)

Would print out the desired output:

>>> [[6, 2, 3], [9, 5, 6]]

Upvotes: 1

Tobias Bruckert
Tobias Bruckert

Reputation: 397

One approach is

my_list = [1,2,3,4,5]
add_item = [2,3]
new_list = [x+1 if i in add_item else x for i, x in enumerate(my_list)]
print(new_list)

Upvotes: 1

Related Questions