Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a time complexity difference between these two methods of list traversal?

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.

like image 271
AlanSTACK Avatar asked Dec 08 '25 14:12

AlanSTACK


1 Answers

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.

like image 186
amit Avatar answered Dec 10 '25 03:12

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!