Sebastian
Sebastian

Reputation: 967

How do I add an integer to just some numbers in a list?

I have a list and I want to add an integer to every value in the list, past the fifth value.

PageNumbers = [30, 50, 80, 120, 160, 200, 240, 280]
PageNumbers = [x+100 for x in PageNumbers]

How do I make it PageNumbers = if PageNumber[index] > 5, then [x+100 for x in PageNumbers] else PageNumber[index].

My desired output is [30, 50, 80, 120, 160, 300, 340, 380]

Upvotes: 1

Views: 86

Answers (6)

iGian
iGian

Reputation: 11183

Just an example using NumPy:

import numpy as np

PageNumbers = np.array([30, 50, 80, 120, 160, 200, 240, 280])

PageNumbers[5:] += 100

print(PageNumbers)
#=> [ 30  50  80 120 160 300 340 380]

Upvotes: 0

BENY
BENY

Reputation: 323226

Just assign it back

PageNumbers[5:]=[x +100 for x in PageNumbers[5:]]
PageNumbers
[30, 50, 80, 120, 160, 300, 340, 380]

Upvotes: 1

Heyran.rs
Heyran.rs

Reputation: 513

for i in range(5, len(PageNumbers)):
    PageNumbers[i] += 100

Upvotes: 1

Tom Lynch
Tom Lynch

Reputation: 913

Use a conditional expression and the enumerate builtin:

>>> PageNumbers = [30, 50, 80, 120, 160, 200, 240, 280]
>>> [x + 100 if i > 4 else x for i, x in enumerate(PageNumbers)]
[30, 50, 80, 120, 160, 300, 340, 380]

Upvotes: 0

Daniel
Daniel

Reputation: 42748

Divide the list into two parts:

PageNumbers = PageNumbers[:5] + [x+100 for x in PageNumbers[5:]]

Upvotes: 2

kyle
kyle

Reputation: 691

Check out enumerate to grab both the index and the value while iterating a list.

This will allow you to do something like the below:

PageNumbers = [30, 50, 80, 120, 160, 200, 240, 280]
PageNumbers = [val + 100 if idx > 4 else val for idx, val in enumerate(PageNumbers)]

*Note that I actually used idx > 4 which means anything past the 5th value (0-index based) as you noted and used in your example. You can, of course, change to use whichever index you'd like.

See a short post and discussion on enumerate here: Python using enumerate inside list comprehension

Upvotes: 3

Related Questions