Forum Archive

Find consecutive elements in a list

craigmrock

Trying to return True if there are duplicate items in a list.
Not working with numbers, and want to allow the user to make a list as long as they want...suggestions?

```
user = input("What's on your list??: ")
def has_consecutive():
items = user.split() #trying to split list into items to compare
if (items[0] == items[+1]): #trying to compare one item to the next to find duplicates
return True #return true if duplicates are found

else:
    return False #return False if no duplicates are found

has_consecutive()```

cvp

@craigmrock try this

def has_duplicate():
    user = '1 2 3 4 2'
    items = user.split()
    for i in range(0,len(items)-1): # loop on items except last one
        if items[i] in items[i+1:]:     # check of i-th item exists in next ones
            return True
    return False
print(has_duplicate())

Checks if duplicates exist but not only consecutive...

        if items[i] == items[i+1]:      # check if i-th item is equal to next one

Will check consecutive duplicates

enceladus
def hasdupelems(l):
    return len(l) != len(set(l))

print(hasdupelems(['ab', 'cd', 'ab', 'ef']))
print(hasdupelems(['ab', 'cd',  'ef']))