1

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
asked Dec 23, 2016 at 17:02
6
  • Insert or replace? Commented Dec 23, 2016 at 17:04
  • for the program i am writing, i need to add, however i would glad to know how to replace too Commented Dec 23, 2016 at 17:04
  • list[1][2] is out of range. list[1] has a length of 2, so you would have to use ppend() Commented Dec 23, 2016 at 17:06
  • Now - I was checking what you meant - list[1][2] is the third element of the 2nd list in the list (named \list`)... Commented Dec 23, 2016 at 17:06
  • 3
    don't name your list as list, that's an inbuilt function in python. Commented Dec 23, 2016 at 17:07

3 Answers 3

2

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

1

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

Thank you! I as gonna go look to how to replace elements just now!
@Badmephisto You're welcome, I added also some examples that you can use to understand better!
1

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.