-1

I have a list RESULT that contains lists. I want to add a list to RESULT only if it does not exist.

So

input = [1,2,3]
RESULT = [[5,6], [4,5,8]]

Now, RESULT.append(input) that gives

RESULT = [[5,6], [4,5,8], [1,2,3]]

Now if I try to append [5,6] it shouldn't be added as its already there.

I cannot use a set here so what's the alternative ?

Alec
  • 8,529
  • 8
  • 37
  • 63
Atihska
  • 4,803
  • 10
  • 56
  • 98
  • What have you tried so far? – G. Anderson Apr 23 '19 at 22:38
  • Why can't you use a set? – mkrieger1 Apr 24 '19 at 08:11
  • @alec_a Yes, I understand but unable to decide which one's actually solved the problem. Kind of solved it in another way but will give another read to the answers and mark :-) – Atihska Apr 25 '19 at 22:27
  • @Atihska Thanks! By the way, if you found a different way to solve it, you might want to post an answer to your own question. It could help future readers (and get you some rep if they're inclined to upvote it) – Alec Apr 25 '19 at 22:28

4 Answers4

3
def add(data_, value):
    if value not in data_:
        data_.append(value)

data = [[5, 6], [4, 5, 8]]
print(data)  # [[5, 6], [4, 5, 8]]
add(data, [1, 2, 3])
print(data)  # {(5, 6), (4, 5, 8), (1, 2, 3)}
add(data, [5, 6])
print(data)  # {(5, 6), (4, 5, 8), (1, 2, 3)}
David Robles
  • 9,477
  • 8
  • 37
  • 47
2

You can use itertools.groupby():

no_dupes = list(ls for ls, _ in itertools.groupby(ls))

Then check against it:

if ls == no_dupes:
     # Do x
Alec
  • 8,529
  • 8
  • 37
  • 63
1

Simplest solution may be to use an if statement to first check if [5,6] is not already in RESULT, and if not, append it, otherwise continue on, possibly report to the user that it was a duplicate and not appended:

myinput = [1,2,3]
RESULT = [[5,6], [4,5,8]]

RESULT.append(myinput)

l = [5,6]

if l not in RESULT:
    RESULT.append(l)
else:
    # Do something with RESULT 
    pass # or
    # print('Duplicate not appended')
    print(f'RESULT: {RESULT}')
    raise(Exception(f'{l} is a duplicate and thus was not appended'))

output:

RESULT: [[5, 6], [4, 5, 8], [1, 2, 3]]
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    raise(Exception(f'{l} is a duplicate and thus was not appended'))
Exception: [5, 6] is a duplicate and thus was not appended
0
input = [1,2,3]
RESULT = [[5,6], [4,5,8]]

suppose after appending RESULT.append(input)

RESULT=[[5,6], [4,5,8], [1,2,3]]

Basic Idea for this particular code:

For checking :

i=0    
count=0
while i<3:
  if input == RESULT[i]:
     count=count+1
  i = i + 1
if count==0:
    RESULT.append(input)
print(RESULT)
Sociopath
  • 13,068
  • 19
  • 47
  • 75
ashishmishra
  • 363
  • 2
  • 14