Reputation: 43
I am trying to generate a list containing a mixture of ascending and descending numbers.
e.g., say you have n=5
. I want to generate a list/array based on n
such that you have:
[0,1,2,3,4,3,2,1,0]
using list comprehension.
I tried doing this:
print [[i+j] for i in range(n)for j in range(n,-1,-1)]
but I can't seem to get it right.
Upvotes: 1
Views: 7312
Reputation: 25974
I know you specified you wanted a list comp, but is it really necessary?
list(range(5)) + list(reversed(range(4)))
(python 3 syntax)
Or, in python2:
range(5) + range(4)[::-1]
or
range(5) + range(3,-1,-1)
I think the first one is more readable, but ymmv.
Upvotes: 5
Reputation: 76725
One-liner:
[i if i < n else 2*(n-1)-i for i in range(2*(n-1) + 1)]
More efficient:
_top = 2*(n-1)
[i if i < n else _top-i for i in range(_top + 1)]
Upvotes: 0
Reputation: 93924
In [27]: n = 5
In [28]: [n-1-abs(i-n+1) for i in range(n*2-1)]
Out[28]: [0, 1, 2, 3, 4, 3, 2, 1, 0]
This one might be more clear
In [36]: [n-abs(i) for i in range(-n,n+1)]
Out[36]: [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
Upvotes: 2