-1

I have a variable x. I need to create a list such as

lst=[0,x,x,2*x,2*x,3*x,3*x,N*x,N*x]

up to any N

Seems like this should be straightforward but I'm kinda stuck. Any help is appreciated.

Respectfully I don't see how this question is a duplicate

update....

So I did this.

import numpy as np

N=4
lst=[0]
x=1.2

for i in np.arange(1,N+1):
    seed=[1,1]
    for j in seed:
        lst.append(i*x)

 lst= [0, 1.2, 1.2, 2.3999999999999999, 2.3999999999999999, 3.5999999999999996, 3.5999999999999996, 4.7999999999999998, 4.7999999999999998]

It feels like a terrible hack.

There has to be a more elegant solution.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Todd
  • 95
  • 5

2 Answers2

1

you can do this like this

>>> n=4
>>> x=1.2
>>> lst=[0,x,x]
>>> lst.extend( i*x for i in range(2,n+1) for _ in range(2) )
>>> lst
[0, 1.2, 1.2, 2.4, 2.4, 3.5999999999999996, 3.5999999999999996, 4.8, 4.8]
>>> 

EDIT

or with one list comprehension and nothing else

>>> n=4
>>> x=1.2
>>> lst=[ i*x for i in range(n+1) for _ in range(2 if i else 1) ]
>>> lst
[0.0, 1.2, 1.2, 2.4, 2.4, 3.5999999999999996, 3.5999999999999996, 4.8, 4.8]
>>> 

(note use xrange if you are in python 2)

Copperfield
  • 8,131
  • 3
  • 23
  • 29
  • Better answer than mine. I'd combine them into `lst = [0] + [i*x for i in range(1,N+1) for _ in range(2)]`. – Mark Ransom Sep 08 '16 at 15:27
  • @MarkRansom what I don't like about that is that as far as I know the `+` operator produce a new copy with both lists, so effectively wasting more space than it needs to by first making the comprehension list and then copy it... but that give a idea to include the zero in list too in just one comprehension – Copperfield Sep 08 '16 at 17:04
0

You can do this with a list comprehension. It isn't as clear as the code you started with though.

>>> N=4
>>> x=1.25
>>> lst = [0] + [i//2 * x for i in range(2, 2*N+2)]
>>> lst
[0, 1.25, 1.25, 2.5, 2.5, 3.75, 3.75, 5.0, 5.0]
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622