How do I add an item number to each number in the list?

Question:

Add an index number to each element of the array in it
for example
I need to output it like this test. 7; 3; 0; -5; 1; 2; 8; 4. The result. 7; 4; 2; -2; 5; 7; 14; 11.

import random
rand_mass = []
n = 10
for i in range(n):
    rand_mass.append(random.randint(-5, 9))

and what should I do next?

Asked By: POG MEE

||

Answers:

You can add the i index to each value that you append to the list +1, since i starts at 0.

import random
rand_mass = []
n = 10
for i in range(n):
    rand_mass.append( random.randint(-5, 9) + (i+1) )
Answered By: Sean

Use a comprehension

import random

n = 10

# if your index starts at 0

rand_initial = [random.randint(-5, 9)   for i in range(n)]
rand_mass    = [rand_initial[idx] + idx for idx in range(n)]

print(rand_initial)
print(rand_mass)
Answered By: DrBwts
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.