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!
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With