Is there a difference in time complexity? Or are they the same? I am not sure how to tell.
list_of_dict = [{'name':'alan', 'age':5}, {'name':'alice', 'age':6}]
# first method
names = []
ages = []
for i in range(len(list_of_dict)):
names.append(list_of_dict[i]['name'])
ages.append(list_of_dict[i]['age'])
# second method
names = [x['name'] for x in list_of_dict]
ages = [x['age'] for x in list_of_dict]
Any assistance or recommendations regarding this issue would be greatly appreciated.
In terms of asymptotic time complexity, they are the same.
Both methods require constant dictionary access (which is constant time on average), for each element in the list, so O(n) for both.
If you care about constants though, it will be hard to tell, and might vary between different interpreters, which might optimize different things.
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