Python dict list difference

Asked 6 days ago, Updated 6 days ago, 2 views

I have a question about the way List and Dict are called in Python.

Personally, I thought that dict and list object calling method were the same, but the result was completely different from what I expected.

I thought both List and Dick would return the result if they found a matching value through repetition, but I checked that Dick calls are faster than List calls (?), and I wonder how this difference can occur.

Isn't it going through the same process in that it finds a matching value?

from time import time

l = range(99999)
t = time()
for i in l:
    if i == 90000:
        a = i
print(time() - t)
>>> 0.006998300552368164
d = {}
for i in l:
    d[i] = 99999999999999999999999999999999999999999999999999
t = time()
a = d[90000]
print(time() - t)
>>> 0

python list dictionary

2022-09-20 13:12

1 Answers

>>> l = list(range(10**7))
>>> s = set(l)
>>> 10**7 in l
>>> 10**7 in s

>>> import time
>>> def test_list_find():
    t0 = time.time()
    for _ in range(100):
        b = 10**7 in l
    print(time.time() - t0)

>>> def test_set_find():
    t0 = time.time()
    for _ in range(100):
        b = 10**7 in s
    print(time.time() - t0)

>>> test_list_find()

>>> test_set_find()

Let me compare the list with the three.

You make a list and three of the same size, and you determine which values are in the list/set. To check the time difference, I timed it repeatedly.

The membership check on the list takes much longer. We're going to take each element out of the list and compare it. So, it will take time in proportion to the size of the list. However, the three are implemented as hash tables, so they search more efficiently. You can study if you need a specific implementation. I had a roughly sorted index, and I thought I'd do a binary research on it, so I moved on.

In dictionaries, whether or not keys exist is repeatedly used very importantly, so dictionary keys will be made of three, not a list. So it's different.

The list and three search times are almost the same as those in the table indexed in the database and those in the table not indexed. If you search without indexing, the application gets really slow. That's right.

2022-09-20 13:12

If you have any answers or tips

© 2022 pinfo. All rights reserved.