Search code examples
pythonlistseparator

How can I add separators to lists of numbers?


I'm having an exercise where it told me to print out each person's favourite numbers. When it came to people with more than one number, I couldn't keep the numbers in one line, separated by commas. Can you suggest a solution?

My code

favourite_numbers = {
    "ha": [20, 10, 4],
    "quynh": [2, 5],
    "nhung": [3, 10, 12],
    "giang": [10],
}

for name, numbers in favourite_numbers.items():
    if len(numbers) == 1:
        for number in numbers:
            print(f"\n{name.title()}'s favourite number is {number}.")
    elif len(numbers) >= 2:
        print(f"\n{name.title()}'s favourite numbers are:")
        for number in numbers:
            print(f"{number}")

The output for a person with multiple numbers looks like this

Ha's favourite numbers are:
20
10
4

I was expecting it to be like this:

Ha's favourite numbers are: 20, 10, 4

Solution

  • You can do this by using two calls to print() when there is more than one number in the value list. In the second call to print() just unpack the list:

    favourite_numbers = {
        "ha": [20, 10, 4],
        "quynh": [2, 5],
        "nhung": [3, 10, 12],
        "giang": [10],
    }
    
    for k, v in favourite_numbers.items():
        s = 's are' if len(v) > 1 else ' is'
        print(f"{k.title()}'s favourite number{s} ", end='')
        print(*v, sep=', ')
    

    Optionally use map/join as follows:

    for k, v in favourite_numbers.items():
        s = 's are' if len(v) > 1 else ' is'
        print(f"{k.title()}'s favourite number{s}", ', '.join(map(str, v)))
    

    Output:

    Ha's favourite numbers are 20, 10, 4
    Quynh's favourite numbers are 2, 5
    Nhung's favourite numbers are 3, 10, 12
    Giang's favourite number is 10