Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make List of Unique Objects in Python

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!

like image 907
James Taylor Avatar asked Aug 09 '15 02:08

James Taylor


1 Answers

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'}]
like image 123
sberry Avatar answered Oct 17 '22 01:10

sberry