Search code examples
pythonpython-3.xlistpython-3.7

Is there a way to check for duplicates in a list?


I have a program i need to create and one of the tasks are to have the user input 5 numbers(integer) for each day of the week (Monday-Friday). For those 5 numbers i need to figure out if there are any duplicates that the user has inputted and display which two days are the duplicates using a single list that contains strings and integers and finally display them. Im new to programming and i would very much appreciate the help!

using python 3.x

Thank you!


Solution

  • You could use a dictionary to keep track of the days for each number. See the following example:

    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    
    # get numbers
    numbers = dict()
    for day in days:
        n = input(f'enter number for day {day}: ')
        if n in numbers:
            numbers[n].append(day)
        else:
            numbers[n] = [day]
    
    # find duplicates
    for n, ds in numbers.items():
        if len(ds) > 1:
            print(f'duplicate number {n} for days', *ds)