-1

[PYTHON] Hello i have to create a list which starts at 1 and ends at 20, and then convert this list into a nested list which should look like this: [[1,2,...,20],[20,19,...1]].

I did only this:

list = []
for i in range(1,21):
    lista.append(i)
    i += 1

which gives me a normal [1, ... 20] list, but I don't know how to change it to a nested list with a reverse list.

martineau
  • 119,623
  • 25
  • 170
  • 301
mkl1337
  • 23
  • 5

5 Answers5

0

You can use a list comprehension to simply do this (don't use list as variable name):

myList = [[x for x in range(1,21)],[y for y in range(21,0,-1)]]
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Create a nested list to begin with:

l = [ [], [] ]
for i in range(20):
    l[0].append(i+1)       # fills the first inner list with 1...20
    l[-1].append(20-i)     # fills the last inner list with 20...1

print(l)

Output:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 
 [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Reverse a list using slicing and concat both list.

arr = [1,2,3,4,5,6,7]
ans = [arr] + [arr[::-1]]
print(ans)

Output:

[[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]
Equinox
  • 6,483
  • 3
  • 23
  • 32
0
my_list = [list(range(1, 21)), list(range(21, 0 ,-1))]
Mark
  • 532
  • 2
  • 6
  • Cheeky answer that I like. But it ignores the "and then convert this list into a nested list " part. – Mr. T Nov 06 '20 at 17:14
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Consider reading [How to Answer](https://stackoverflow.com/help/how-to-answer) and [edit] your answer to improve it. – blurfus Nov 06 '20 at 18:47
0

Simple:

>>> x = [i for i in range(1, 21)]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> r = [x, x[::-1]]
>>> r
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]]
777moneymaker
  • 697
  • 4
  • 15