wowo
wowo

Reputation: 11

List Comprehension and "not in" keywords

Working on some basic programming exercises but was somewhat confused to find that the following code snippets do not return the same values. The list comprehension syntax seems to almost ignore the "not in" keywords I used on the list being created from the list comprehension itself. Is this behavior not allowed? The function simply finds if a 1, 2, and 3, exist somewhere in a list of integers.

# Working, no list-comprehension
def array123(lst):
  my_lst = []
  for num in lst:
    if num not in my_lst and (num == 1 or num == 2 or num == 3):
      my_lst.append(num)
  if sorted(my_lst) == [1, 2, 3]:
    return True
  else:
    return False

# List Comprehension 
def array123(lst):
  my_lst = []
  my_lst = [num for num in lst if num not in my_lst and (num == 1 or num == 2 or num == 3)]
  if sorted(my_lst) == [1, 2, 3]:
    return True
  else:
    return False

Upvotes: 1

Views: 205

Answers (3)

SparkAndShine
SparkAndShine

Reputation: 18007

In the list comprehensions version, if num not in my_lst always returns True because my_lst is [] at that time.

# List Comprehension 
def array123(lst):
  my_lst = []

  my_lst = [num for num in lst 
                if num not in my_lst    # always returns True for `my_lst=[]`
                        and (num == 1 or num == 2 or num == 3)]

  print(my_lst)

# Demo 
array123([1, 2, 3, 1, 2, 3])
# Output
[1, 2, 3, 1, 2, 3]

You probably want to check if the unique elements of a list are 1, 2, 3. Use set, here it is.

my_lst = [1, 2, 3, 1, 2, 3]
b = set(my_lst) == set([1, 2, 3])   # True

my_lst = [1, 2, 3, 1, 2, 4]
b = set(my_lst) == set([1, 2, 3])   # False

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78556

Your condition not in my_list will be always True. Since you're creating unique elements you should use a set comprehension.

my_set = {num for num in lst if num == 1 or num == 2 or num == 3}

Your if-or conditions can be reduced to:

my_set = {num for num in lst if num in (1, 2, 3)}

And then you convert your set into a list

my_list = list(my_set)

Upvotes: 1

aghast
aghast

Reputation: 15310

Or use sets:

#!python3
_SET123 = {1,2,3}

def array123(iterable):
    return set(i for i in iterable if i in _SET123) == _SET123



for x in "123", (1,2,2,2), [1,2,3], {1:"one", 3:"two", 2:"three"}:
    print(x, array123(x))

Upvotes: 1

Related Questions