birthofearth
birthofearth

Reputation: 396

Add integers to specific items in a list in python?

I would like to add some integer to a range of items in a list in python.

I know that this is correct if you want to add an integer to every item in a list:

A = 2
B = 5
C = 6
mylist = [1,2,3,4,5,6,7,8]
mylist[:] = [i+C for i in mylist]
print mylist

but I would like to add C to items A through B. so that instead of resulting in this list:

mylist = [7,8,9,10,11,12,13,14]

I would get this list:

mylist = [1,2,*9*,*10*,*11*,*12*,7,8]

is there a way to do this?

Thanks

Upvotes: 1

Views: 169

Answers (4)

djas
djas

Reputation: 1023

mylist[A:B+1] = [i+C for i in mylist[A:B+1]]

Upvotes: 0

Hamatti
Hamatti

Reputation: 1220

In addition to @iCodez answer, if you don't want to modify the original, you can use if-else

A = 2
B = 5
C = 6
oldlist = [1,2,3,4,5,6,7,8]
mylist = [x+C if A <= i <= B else x for i, x in enumerate(oldlist)]

Upvotes: 1

satoru
satoru

Reputation: 33235

for i in range(A, B+1):
    mylist[i] += C

Upvotes: 1

user2555451
user2555451

Reputation:

Assign to a slice of the list:

>>> A = 2
>>> B = 5
>>> C = 6
>>> mylist = [1,2,3,4,5,6,7,8]
>>> mylist[A:B+1] = [i+C for i in mylist[A:B+1]]
>>> mylist
[1, 2, 9, 10, 11, 12, 7, 8]
>>>

Upvotes: 6

Related Questions