Chris
Chris

Reputation: 23

Dynamic triple nested list in Python

I'm looking to create a triple nested list in Python. This is meant to be a list of N individuals, who each have a vocabulary of L words, and for each word I want to store an ending (e) and a time since the individual has last used the word (t). I know how to do a double nested list, essentially giving one individual with a vocabulary:

individual_vocab = [[e,t] for L in range(L)]

if I had five words, this would give me something like this:

[[e,t,],[e,t],[e,t],[e,t],[e,t]]

and i could change the ending of one word without changing another.

Now, I want to initialise a population of individuals each with this vocabulary, and it's fine (in fact, preferable) if this is the same at the start, but they have to be dynamic. My first instinct is this:

population =[individual_vocab for N in range(N)]

But of course, the problem is that this isn't dynamic: all the individuals in the population in this case are a direct copy of one another (i.e., point to individual_vocab) and therefore won't change independently, such that if I do this with an N of 3, then try to assign a new value to the word ending of the first word of the first individual, I get this (where the ones are e and the 2s are t), which changes the ending of the first word for every individual:

population[0][0][0] = "new ending"

population

[[['new ending', 2], [1, 2], [1, 2], [1, 2], [1, 2]], [['new ending', 2], [1, 2], [1, 2], [1, 2], [1, 2]], [['new ending', 2], [1, 2], [1, 2], [1, 2], [1, 2]]]

how can I efficiently make a dynamic list of lists of lists?

Upvotes: 0

Views: 1031

Answers (1)

japreiss
japreiss

Reputation: 11251

use the copy module:

import copy

individual_vocab = [[e,t] for l in range(L)]

population = [copy.deepcopy(individual_vocab) for n in range(N)]

Adding my opinion - I think this level of nesting must make you the Python equivalent of a Three Star C Programmer. I'd start working with classes at this point to keep your code readable.

Upvotes: 1

Related Questions