Dealing with empty lists in Python

Question:

I have two lists A,B and I am mapping the values using map() as shown below. This works fine when both the lists have elements. However, when A,B are both empty, I get an error. I also present the expected output.

A=[]
B=[]
tol=1e-12

CA, CB = map(list, zip(*((a, b) for a, b in zip(B, A) if a[0]>tol)))

print(CA)
print(CB)

The error is

in <module>
    CA, CB = map(list, zip(*((a, b) for a, b in zip(B, A) if a[0]>tol)))

ValueError: not enough values to unpack (expected 2, got 0)

The expected output is

CA=[]
CB=[]
Asked By: modishah123

||

Answers:

if len(A) == 0 or len(B) == 0:
    CA = []
    CB = []
else:
    CA, CB = map(list, zip(*((a, b) for a, b in zip(A, B) if a[0] > tol)))
Answered By: angwrk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.