Need explain a convoluted Python code in 5.3

#1

Hello,

So in 5.3: Multiply Two Arbitrary Precision Integer solution, there is an interesting Python code to remove the leading zeros of the Result array

result = result [ next((i for i, x in enumerate(result) if x != 0), len(result)): ] or [ 0 ]

The input would be [0, 9, 0, 4, 7, 0] and output would be [9, 0, 4, 7, 0].

Could anybody break down the code and explain what each part of the code does?

Thanks!

1 Like

#2

Hi @tml,

Thanks for the question, and following is my breakdown:

next((i for i, x in enumerate(result) if x != 0), len(result)) returns the first non-zero digit index in result otherwise returns len(result). Then we use result[first_non_zero_idx:] to get the the part starting with non-zero. However, for the case like [0, 0, …, 0], we don’t want to return [], so that is the reason or [0] comes to save this situation.

It is a little bit to understand this as it combines several concepts in one-line to make it very “pythonic”, and personally I think with some practice, it will become part of nature of writing Python.

1 Like