josephting
josephting

Reputation: 2665

Create an array of size n with initialized value

In python, it's possible to create an array of size n with [] * n or even initialize a fixed value for all items with [0] * n.

Is it possible to do something similar but initialize the value with 500n?

For example, create an array with size of 10 would result in this.

[0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500]

I can easily achieve this with a variable and a for loop as shown below but I would like optimize this in one go to pass into Robot Framework.

arr = [0] * 10
for i, v in enumerate(arr):
  arr[i] = 500 * i

Upvotes: 4

Views: 14779

Answers (3)

pyano
pyano

Reputation: 1978

It's allways a good idea to use numpy arrays. They have more fuctionalites and are very fast in use (vectorized form, and fast compiled C-code under the hood). Your example with numpy:

import numpy as np

nx = 10
a = 500*np.arange(nx)
a

gives:

array([   0,  500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500])

Upvotes: 1

Nenri
Nenri

Reputation: 528

The other answer gives you a way, here's another :

list(range(0, 500*n, 500))

Upvotes: 2

Netwave
Netwave

Reputation: 42678

Use a simple comprehension:

[i*500 for i in range(n)]

Upvotes: 14

Related Questions