Performing a list operation in Python


I am removing J1 from J. Corresponding to the removed indices, I want to alter Ci[1] and append to Ci as shown below but I am getting an error. I also present the expected output.

J=[2, 6, 9, 10]
l.append([x for x in J if x not in J1])

Ci = [[0, 0, 0, 0], [10, 30, 50, 80]]
A=Ci[1]([x for x in J if x not in J1])

The error is

in <module>
    A=Ci[1]([x for x in J if x not in J1])

TypeError: 'list' object is not callable

The expected output is

[[[0, 0, 0, 0], [10, 30, 50, 80]],[[10, 50]]]
Asked By: isaacmodi123



You can use zip to iterate on two lists simultaneously:

A = [Ci, [x for x,y in zip(Ci[1],J) if y not in J1]]
# [[[0, 0, 0, 0], [10, 30, 50, 80]], [10, 50]]
Answered By: Stef

You can collect the indices first,

lidx = [i for i in range(len(J)) if J[i] not in J1]
A = [Ci, [Ci[1][i] for i in lidx]]
Answered By: rustyhu
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.