Home > OS >  For-loop not looping multiple times in range of a list
For-loop not looping multiple times in range of a list

Time:11-06

expected boolean to return true but received false

def thing(a):
  b = 1
  c = 2
  for x in range(len(a)):
    if b == a[x:x 1] and c == a[x 1:x 2]:
      return True
    else:
      return False
print(thing([1,3,4,1,2]))

CodePudding user response:

You're comparing numbers to list slices, they can never be equal, even if you're just slicing a single element. You need to compare with specific list indexes, not slices.

Subtract 1 from the list length so you don't get an invalid index when you access a[x 1] at the end.

def thing(a):
    b = 1
    c = 2
    for x in range(len(a)-1):
        if b == a[x] and c == a[x 1]:
            return True
    return False

print(thing([1,3,4,1,2]))

CodePudding user response:

Your iteration isn't comparing the actual contents of the list to b and/or c. A simpler way of doing what you're trying to do is to iterate over a zip of the list with a slice of itself:

>>> def thing(a):
...     b = 1
...     c = 2
...     for x, y in zip(a, a[1:]):
...         if (x, y) == (b, c):
...             return True
...     return False
...
>>> thing([1,3,4,1,2])
True
>>> thing([1,3,4,1,3])
False

CodePudding user response:

IIUC, looks like you want to check if two consecutive numbers are found in the list. Here is a fix of your code:

def thing(a):
  b = 1
  c = 2
  for x in range(len(a)-1):
    if b == a[x] and c == a[x 1]:
      return True
  return False
print(thing([1,3,4,1,2]))

Errors:

1- you should only return False after the loop

2- you need to loop until length - 1 as you take x 1, else you would hat an IndexError

3- you should only slice the element you want, not a range, if you're comparing to an element

alternating with slicing as list:
def thing(a):
  b = 1
  c = 2
  for x in range(len(a)-1):
    if a[x:x 2] == [b, c]:
      return True
  return False
  • Related