Adding items to nested lists Python

I’ve got 4 groups each with 2 subgroups
image

I want to add, “cat” to index[1][1]

How do I do this? I’ve tried various ways but nothing seems to work!

image

image

I’ve also tried insert.

Looks like the first method is working - instead of building an empty list define it as a single string and see what you get.

Not sure I follow.

I want n lists each with 2 sublists… Then I want to add things to those specific lists.

How’s that work with a string?

hello, I think you should use extend rather than append, Mr. Poupin posted a message a few days ago that I’m a computer user, I’m researching
Edit:

Cordially
christian.stan

1 Like

Hi @Alien

There is problem with your list (at initialization /construction), see this post

1 Like

Here is


Groups=[[[],[]]]*4

Groups[1][1].extend([[],'cat'])

OUT = Groups


Thank you for the regular contributions of knowledge Mr. Poupin

cordially
christian.stan

1 Like

You have added ‘cat’ to every list, not into the sublist.

I want ‘cat’ to appear in one list at a specific index.

Ok I’m a real babache, I’ll take a closer look at Mr. Poupin’s post

cordially
christian.stan

I want a way to add to a specific index :frowning:

image
This is doning hat I hink you’re asking for.

Instead of an empty list, put a variable in each list to confirm.

I clarified my answer just before you pressed send :smiley:

See my post above.

Don’t define groups as *4 of the same list; it looks like you’re duplicating the items in memory so the alterations are duplicating as well.

So:
groups = [ [ [1], [2] ], [ [3],[4] ], [ [5],[6] ], [ [7], [8] ] ]

That’d be an issue because I want n groups.
Not specifically 4 every time.

Then don’t define by it *4.

groups = []
[ groups.append([ [],[] ]) for i in range(n) ]
3 Likes

Jacob, you are a genius!

Thank you! :partying_face:

If you ever want to keep the structure of your list with your empty

Force to add an Empty in the addition to keep it.


Cordially
christian.stan

1 Like