+ 3

I tried to turn a regular list into a 2 dimensional list and and add values to those lists but failed,why?

https://code.sololearn.com/cMfH7m4TDRyY/?ref=app

5th Feb 2022, 12:47 PM
Lenoname
13 odpowiedzi
+ 3
Maybe this does what you want: a = [] a.append([]) a.append([]) a[0].append(1) a[1].append(6) print(a)
5th Feb 2022, 1:07 PM
Paul
Paul - avatar
5th Feb 2022, 2:06 PM
Azamat Shermatov
Azamat Shermatov - avatar
5th Feb 2022, 2:12 PM
Azamat Shermatov
Azamat Shermatov - avatar
+ 3
No, when a = [6, 5] and you append [2] the output should be [6, 5, [2]] If you want [[6, 5], [2]] you can use one of these ways: a = [[6, 5]] a.append([2]) or a = [] a.append([6, 5]) a.append([2]) or a = [] a.append([]) a[0].append(6) a[0].append(5) a.append([2])
5th Feb 2022, 3:41 PM
Azamat Shermatov
Azamat Shermatov - avatar
+ 2
Line 4: Not arr[1].append(6), must be arr[0].append(6)
5th Feb 2022, 12:52 PM
Azamat Shermatov
Azamat Shermatov - avatar
+ 2
arr = [] arr.append([1]) arr.append([6]) print(*arr)
5th Feb 2022, 2:02 PM
Azamat Shermatov
Azamat Shermatov - avatar
+ 2
Lenoname Think of it as a list of list. Your list index will now be of form: a[x][y] where x is the index relative to a and y is the index relative to a[x] you just have to use the proper index. in you example, you have: a = [6, 5] and you want to have: a = [[6, 5],[2]] you would actually have to create a new list: a = [a, [2]]👈 🔹because a = [6, 5] is not a = [[6, 5]] if: a = [[6, 5]] then yes, a.append([2]) would give a = [[6, 5],[2]] https://code.sololearn.com/cgFrEb3piq8A/?ref=app
5th Feb 2022, 9:47 PM
Bob_Li
Bob_Li - avatar
+ 1
Hi! That’s because you trying to assign a value to a list that dosen’t exist : a[1] does not exist; just a[0].
5th Feb 2022, 12:55 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
But didnt i add a dimension with a.append([ ])?
5th Feb 2022, 1:06 PM
Lenoname
+ 1
To be shure, try to print(a) to look at it. If you not happy, try something else.
5th Feb 2022, 1:08 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
Works fine if i replace [1] with [0], but as far as i know two dimensional lists come in form of: listA=[1,3,4],[3,6,7],[7,5],…. I just want to add another [ ] to the one dimensional list so that it becomes two dimensional and put numbers in it with .append.
5th Feb 2022, 1:49 PM
Lenoname
+ 1
In short i wanted: [1],[6] to be printed.
5th Feb 2022, 1:50 PM
Lenoname
+ 1
Azamat Shermatov lets say a=[6,5] when i use a.append([2]) the output is [6,5,[2]] But It should be [[6,5],[2]]
5th Feb 2022, 2:36 PM
Lenoname