0

Sorry if this is a dup, I couldn't find it anywhere.

If you start with a dictionary that has two keys pointing to an identical list, e.g.:

In [1]: value = [1,2,3,4]

In [2]: example_dict = {'key1':value, 'key2':value}

In [3]: example_dict
Out[3]: {'key1': [1, 2, 3, 4], 'key2': [1, 2, 3, 4]}

How does python store this in memory? Are the values merely pointers to the original list? Or is each value a new instantiated list. I'm curious because I'm building a very large lookup table where each element in a list is a key in a dictionary pointing to the list where it was derived. For example (using the same example as above), my dictionary's entries would look something like this:

In [4]: value = [1,2,3,4]

In [5]: example_dict = {1:value, 2:value, 3:value, 4:value}

In [6]: example_dict
Out[6]: {1: [1, 2, 3, 4], 2: [1, 2, 3, 4], 3: [1, 2, 3, 4], 4: [1, 2, 3, 4]}

Since this will be a table with over 10^6 entries, where each value will be a list of 50+ elements, I'd obviously like to minimize list duplication (and therefore minimize the amount of memory used).

martineau
  • 119,623
  • 25
  • 170
  • 301
lstbl
  • 527
  • 5
  • 17
  • 3
    You can easily demonstrate this yourself: `example_dict['key1'].append(5)` then `print(example_dict['key2'])`. If every key shares the same mutable value object, although that will minimise memory it will also probably lead to somewhat unexpected behaviour... – jonrsharpe Sep 13 '16 at 15:59
  • Yup, that answers it. I was thinking python would probably do it that way, but wasn't sure how to find the answer. Much appreciate the simple solution. – lstbl Sep 13 '16 at 16:02

0 Answers0