zelenov aleksey - 1 year ago 118
Python Question

# how to check list before adding items?

I have a list of [i,j] values:

``````lst = [[1,2],[1,3],[3,4],[4,6]]
#[1,2] means that i=1 and j=2
``````

`[a,b]`
, for example
`[6,1]`
, how can I add values to my lst by condition

`[a,b]`
only if
`[a,j]`
does not exists in a set)

So element
`[6,1]`
`[1,2]`
and
`[1,3]`
exists

Thanks in advance for any help!

You could just iterate the list and check whether for `any` of the items `(i,j)` in the list, `i` is the same as `b` in the item `(a,b)` you want to add. (At least that's how I understood your condition, but if the condition is slightly different, this should be easy to adapt accordingly.)

``````def cond_add(lst, item):
a, b = item
if not any(i == b for (i, j) in lst):
lst.append(item)

lst = [[1,2],[1,3],[3,4],[4,6]]
print(lst)
``````

If you want to add multiple elements, it would pay to create a `set` from the first elements, so you can do the check in constant time for each individual item. (You could do the same for adding individual elements, but you'd have to update the set after each item.)

``````def cond_add_many(lst, items):
first = set(i for (i, j) in lst)
lst.extend((a,b) for (a,b) in items if b not in first)

lst = [[1,2],[1,3],[3,4],[4,6]]
Afterwards, in both cases, `lst` is `[[1, 2], [1, 3], [3, 4], [4, 6], (6, 5)]`