1

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]

codeforester
  • 39,467
  • 16
  • 112
  • 140
Sebastian
  • 957
  • 3
  • 15
  • 27

6 Answers6

3

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

kyle
  • 691
  • 1
  • 7
  • 17
2

Divide the list into two parts:

PageNumbers = PageNumbers[:5] + [x+100 for x in PageNumbers[5:]]
Daniel
  • 42,087
  • 4
  • 55
  • 81
1
for i in range(5, len(PageNumbers)):
    PageNumbers[i] += 100
Heyran.rs
  • 501
  • 1
  • 10
  • 20
1

Just assign it back

PageNumbers[5:]=[x +100 for x in PageNumbers[5:]]
PageNumbers
[30, 50, 80, 120, 160, 300, 340, 380]
BENY
  • 317,841
  • 20
  • 164
  • 234
0

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]

Tom Lynch
  • 893
  • 6
  • 13
0

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]
iGian
  • 11,023
  • 3
  • 21
  • 36