4

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
1
  • 3
    len([] * n) == 0, and those are lists. But why not list(range(0, 500 * n, 500))? Or [500 * index for index in range(n)]? Commented Mar 8, 2019 at 8:13

3 Answers 3

14

Use a simple comprehension:

[i*500 for i in range(n)]
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

1

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])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.