q0987
q0987

Reputation: 35982

Which way to append dict to list is more efficient

# Method one
array_a = []
a = {}
for i in range(5):
    a = {}
    a[str(i)] = i
    array_a.append(a)
print(array_a)
# [{'0': 0}, {'1': 1}, {'2': 2}, {'3': 3}, {'4': 4}]

# Method two    
from copy import deepcopy
array_b = []
b = {}
for i in range(5):
    b.clear()
    b[str(i)] = i
    array_b.append(deepcopy(b))
print(array_b)
# [{'0': 0}, {'1': 1}, {'2': 2}, {'3': 3}, {'4': 4}]

I would like to know which one of above is more efficient. And, if you have a better one, please let me know.

Upvotes: 2

Views: 292

Answers (2)

Austin Marshall
Austin Marshall

Reputation: 3107

Here's a one-liner that should also be more efficient:

array_a.extend([{str(i): i} for i in xrange(5)])

Or via map():

array_a.extend(map(lambda i: {str(i): i}, xrange(5)))

Upvotes: 1

Jasmijn
Jasmijn

Reputation: 10452

The difference is not relevant. Both need to create a new dict each time. Since the first is clearer, it is preferable over the second method.

My suggestion would be a list comprehension:

array_c = [{str(i): i} for i in range(5)]

Upvotes: 7

Related Questions