return True if at least one item in a list is 2 or 3

1

In a list of 2 integers I want True to return if it contains a 2 or a 3 with the following code:

 def has23(nums):
  for i in range(len(nums)):
    if nums[i] == 2 or nums[i] == 3:
      return True
    else:
      return False

For example, if I try this:

print(has23([5, 3]))

Return:

False
    
asked by José Ignacio 01.10.2018 в 01:43
source

2 answers

3

The first iteration for the list of your example ( [5, 3] ) gets the 5 from the list, which triggers in:

if 5 == 2 or 5 == 3:
    return True
else:
    return False

The if is obviously not fulfilled, so it enters the else and the function returns False and ends without even checking the rest of the items in the list. Keep in mind that any return statement that executes in any part of a function causes the execution of the same to end at that same point, regardless of the code that remains to be executed.

The solution is as simple as eliminating else , return True only if the if is met, otherwise go to the next element without more and just return False when the iteration on the list ends (if no if was fulfilled is because no element is a 2 or a 3):

def has23(nums):
    for i in range(len(nums)):
        if nums[i] == 2 or nums[i] == 3:
            return True
    return False

On the other hand, do not use indexed and range to iterate over the list, it is more efficient and "pitonic" to use a for in :

def has23(nums):
    for n in nums:
        if n == 2 or n == 3:
            return True
    return False
    
answered by 01.10.2018 / 02:16
source
1

Let's analyze your solution with the entry: [5, 3]

When i = 0 then num[i] is 5 , so the if nums[i] == 2 or nums[i] == 3: is false so the else will be executed, and the else returns False, and remember that when called return the function is finished, that prevents it from being analyzed when i = 1 . For the above you get that answer.

On the other hand, do not use:

for i in range(len(nums)): 

but you can use the following:

for num in nums:

which is more readable.

A possible solution using the logic of iterating can be the following:

def has23(nums):
    for num in nums:
        if num == 2 or num ==3:
            return True
    return False

That is, if at least num is 2 or is 3 is returned otherwise iterates, and if nothing is returned in the loop False returns at the end.

But python has other instructions such as any and all , the first one returns True if in the list there is at least one True and in other cases False, and the second only returns True if all are True. And also the instruction in that used in an if returns True if an element is in an iterable one. Using the above we obtain:

def has23(nums):
    return any(val in nums for val in (2, 3))
    
answered by 01.10.2018 в 02:20