7

It is possible to 'fill' an array in Python like so:

> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I wanted to use this sample principle to quickly create a list of similar objects:

> a = [{'key': 'value'}] * 3
> a
[{'key': 'value'}, {'key': 'value'}, {'key': 'value'}]

But it appears these objects are linked with one another:

> a[0]['key'] = 'another value'
> a
[{'key': 'another value'}, {'key': 'another value'}, {'key': 'another value'}]

Given that Python does not have a clone() method (it was the first thing I looked for), how would I create unique objects without the need of declaring a for loop and calling append() to add them?

Thanks!

2
  • 2
    FWIW, the copy.copy() function can be used to "clone" many kinds of existing Python objects. In addition, a number of mutable objects (deques, sets, dicts) have a copy() method. The list object grew a copy() method in Python 3. Aug 9, 2015 at 2:54
  • Since the question was closed, I'll have to use a comment to answer the interesting part of your question, "how can you do this without a for-loop and append?" Here is what you could do: d = {'key': 'value'}; import copy; from itertools import repeat; a = list(map(copy.copy, repeat(d, 10))). When a copy() method is available, it would be faster still to use starmap thusly: a = list(starmap(d.copy, repeat((), 10))). Aug 9, 2015 at 3:03

1 Answer 1

3

A simple list comprehension should do the trick:

>>> a = [{'key': 'value'} for _ in range(3)]
>>> a
[{'key': 'value'}, {'key': 'value'}, {'key': 'value'}]
>>> a[0]['key'] = 'poop'
>>> a
[{'key': 'poop'}, {'key': 'value'}, {'key': 'value'}]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.