Skip to content

Instantly share code, notes, and snippets.

@malfet
Last active March 17, 2025 22:58
Show Gist options
  • Save malfet/a611d93f271f4cf6e0a48ff8d2f6bca7 to your computer and use it in GitHub Desktop.
Save malfet/a611d93f271f4cf6e0a48ff8d2f6bca7 to your computer and use it in GitHub Desktop.
import dis
import timeit
def list_to_dict_1(l):
rc = {}
for idx, v in enumerate(l):
rc[v] = idx
return rc
def list_to_dict_2(l):
return {v: idx for idx, v in enumerate(l)}
if __name__ == "__main__":
x = [str(i) for i in range(10_000)]
for f in (list_to_dict_1, list_to_dict_2):
print(f.__name__, timeit.timeit(lambda:f(x), number=5000))
dis.dis(f)
@malfet
Copy link
Author

malfet commented Mar 17, 2025

Using CPython-3.10 produces following:

list_to_dict_1 2.231924040999729
  4           0 BUILD_MAP                0
              2 STORE_FAST               1 (rc)

  5           4 LOAD_GLOBAL              0 (enumerate)
              6 LOAD_FAST                0 (l)
              8 CALL_FUNCTION            1
             10 GET_ITER
        >>   12 FOR_ITER                 8 (to 30)
             14 UNPACK_SEQUENCE          2
             16 STORE_FAST               2 (idx)
             18 STORE_FAST               3 (v)

  6          20 LOAD_FAST                2 (idx)
             22 LOAD_FAST                1 (rc)
             24 LOAD_FAST                3 (v)
             26 STORE_SUBSCR
             28 JUMP_ABSOLUTE            6 (to 12)

  7     >>   30 LOAD_FAST                1 (rc)
             32 RETURN_VALUE
list_to_dict_2 2.1987981670099543
 12           0 LOAD_CONST               1 (<code object <dictcomp> at 0x102a2bcb0, file "/Users/nshulga/test/listtodicdis.py", line 12>)
              2 LOAD_CONST               2 ('list_to_dict_2.<locals>.<dictcomp>')
              4 MAKE_FUNCTION            0
              6 LOAD_GLOBAL              0 (enumerate)
              8 LOAD_FAST                0 (l)
             10 CALL_FUNCTION            1
             12 GET_ITER
             14 CALL_FUNCTION            1
             16 RETURN_VALUE

Disassembly of <code object <dictcomp> at 0x102a2bcb0, file "/Users/nshulga/test/listtodicdis.py", line 12>:
 12           0 BUILD_MAP                0
              2 LOAD_FAST                0 (.0)
        >>    4 FOR_ITER                 7 (to 20)
              6 UNPACK_SEQUENCE          2
              8 STORE_FAST               1 (idx)
             10 STORE_FAST               2 (v)
             12 LOAD_FAST                2 (v)
             14 LOAD_FAST                1 (idx)
             16 MAP_ADD                  2
             18 JUMP_ABSOLUTE            2 (to 4)
        >>   20 RETURN_VALUE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment