why this python code: original = [0] * (m * n) for i in range(0, len(original), n):…
- User
why this python code: original = [0] * (m * n) for i in range(0, len(original), n): res.append(original[i : i + n]) is faster than this: original = [0] * (m * n) res = [[original[n * i + j] for j in range(n)] for i in range(m)]
- Assistant
The first code snippet is faster because it uses fewer Python operations and takes advantage of Python's list slicing, which is implemented in C and therefore more efficient than Python loops.
-
The first code snippet employs a single for loop to iterate over the
originalarray with a step size ofn. This loop runsmiterations (mequalslen(original)//n). In each iteration, it does a slice operation with O(n) complexity. Overall complexity is O(m*n). -
The second code snippet involves two nested list comprehensions which result in
mouter iterations andninner iterations. For each iteration, it calculates the index (n*i + j) and fetches the corresponding element from theoriginalarray. This results in overall complexity of O(m*n).
Both approaches have the same complexity of O(m*n), but the first one benefits from list slicing implemented in C, which is faster than iterating through the lists in Python.
Remember that Python is an interpreted language, and built-in operations (C-implemented) are generally faster than custom loops due to lower-level optimizations. So, the first code snippet is faster primarily because it uses list slicing, reducing the overhead of Python loops and making it run more efficiently.
-
- User
So how to learn all (or at least as many as possible) those unobvious python specifics which can lead to such performance increase? For example I know that functools.reduce() function from python is not written in C and can be slower than for loop so it it would be wrong in some cases to use functools.reduce(). This leads to a contradictory conclusion that it is not always better to use python built in methods. But how to become better at recognising in which case it is better to use built in method and in which case it is not? What resources could be used to learn this? Can you provide with some more examples where using python built-in functions can replace for loops or other constructions?
- Assistant