zelenov aleksey - 6 months ago 28

Python Question

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

and add new elenemt

`[a,b]`

`[6,1]`

(add element

`[a,b]`

`[a,j]`

So element

`[6,1]`

`[1,2]`

`[1,3]`

Thanks in advance for any help!

Answer

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]]
cond_add(lst, [6,1])
cond_add(lst, [6,5])
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]]
cond_add_many(lst, [[6,1], [6,5]])
print(lst)
```

Afterwards, in both cases, `lst`

is `[[1, 2], [1, 3], [3, 4], [4, 6], (6, 5)]`