0

I have two variables n1 and n2 that gives random numbers in a range and is always n1 < n2

I want to make two lists:

First list that has all of the values of n1 and n2 in increasing order
Second list that has all of the values of n2 and n1 in decreasing order

So I tried like this

Li1 = list(range(n1,n2))
Li2 = list(range(n2,n1))

But what I get is this:

Li1: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
Li2: []

The second list is always empty. But it suppose to be like Li1 but in decreasing order

Liviosah
  • 325
  • 2
  • 11

4 Answers4

3

You need to specify the step for the range. It defaults to 1, you're looking for -1. Positive int's count up, whereas you're tryig to count down.

Li2 = list(range(n2,n1, -1))

Refer to the docs or a search for questions before you ask here as likely it's been asked already or the docs already have great explanations.

Jab
  • 26,853
  • 21
  • 75
  • 114
1

You should add -1 as a third argument to range() function

code:

n1 = 10
n2 = 30

print(list(range(n1, n2)))
print(list(range(n2 - 1, n1 - 1, -1)))

what you get:

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]
Andrey Kachow
  • 936
  • 7
  • 22
0

You can also reverse Li1 by doing:

Li2 = Li1[::-1]

It is not the fastest solution. But I think it's a useful trick.

Yaozhi Lu
  • 18
  • 3
0

To have the 'n2' in the list:

Li1 = list(range(n1,n2+1))

and:

Li2 = list(reversed(Li1))
VPfB
  • 14,927
  • 6
  • 41
  • 75