Say I have 2 lists:
list = [[1, 2, 3], [4, 5]]
a = 6
Is there anyway I can put a
into the spot list[1][2]
?
ettanany
20k9 gold badges49 silver badges64 bronze badges
3 Answers 3
Yes, you can just do:
lst[1].append(a)
lst
# [[1, 2, 3], [4, 5, 6]]
answered Dec 23, 2016 at 17:04
Sign up to request clarification or add additional context in comments.
Comments
To add an element, try:
my_list[1].append(a)
To replace an element:
my_list[1][1] = a # This will replace 5 by 6 in the second sub-list
Example of append:
>>> my_list = [[1, 2, 3], [4, 5]]
>>> a = 6
>>> my_list[1].append(a)
>>> my_list
[[1, 2, 3], [4, 5, 6]]
Example of replace:
>>> my_list = [[1, 2, 3], [4, 5]]
>>> a = 6
>>> my_list[1][1] = a
>>> my_list
[[1, 2, 3], [4, 6]]
Note: You should not use list
to name your variable, because it would replace the built-in type list
.
answered Dec 23, 2016 at 17:06
2 Comments
Badmephisto
Thank you! I as gonna go look to how to replace elements just now!
ettanany
@Badmephisto You're welcome, I added also some examples that you can use to understand better!
Instead of using list=[[1,2,3],[4,5]]
(since list is a function in python) let's have
l=[[1,2,3],[4,5]]
Now there is no l[1][2]
as yet.
If we try to access it we get
>>> l[1][2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
We can append this element
l[1].append(a)
Now we can access it
>>> l[1][2]
6
and we can change it:
>>> l[1][2] = 44
>>> l
[[1, 2, 3], [4, 5, 44]]
answered Dec 23, 2016 at 17:09
Comments
lang-py
list[1][2]
is out of range.list[1]
has a length of 2, so you would have to useppend()
list[1][2]
is the third element of the 2nd list in the list (named \list`)...list
, that's an inbuilt function in python.