Quiz
What's the difference between the following code?
For loop:
for idx in range(numRows):
for ch in each_rows[idx]:
all_chars.append(ch)
Extend:
for idx in range(numRows):
all_chars.extend(each_rows[idx])
Answer
Using extend is faster.
Here's a quick comparison:
+--------------------+----------------------+------------------+
| Perspective | append + double loop | extend |
+--------------------+----------------------+------------------+
| Big-O complexity | O(N) | O(N) |
| Python-level loops | Many | Few |
| C-level processing | Less | More (faster) |
| Element copying | No | No |
+--------------------+----------------------+------------------+
list_extend: https://github.com/python/cpython/blob/main/Objects/listobject.c