modishah123
modishah123

Reputation: 39

Dealing with empty lists in Python

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=[]

Upvotes: 0

Views: 97

Answers (1)

angwrk
angwrk

Reputation: 420

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)))

Upvotes: 1

Related Questions