Using (len) with an If statement

I have written a basic program that outputs my friends’ favourite programming languages. I now need to tidy the grammar so that where a friend has only one favourite language, the output reads “favourite language is” instead of “favourite languages are”

I was advised to “check length of language list, if length 1 use singular form, if 2 or more use other form, set these to a single variable that can be dropped into the print statement” Unfortunately I have no idea how to do that.

Can anyone assist please?

Thankyou in advance,

Si

favourite_languages = {
‘jen’ : [‘python’, ‘ruby’],
‘sarah’ : [‘c’],
‘edward’ : [‘ruby’, ‘go’],
‘phil’ : [‘python’, ‘haskell’],
}

for name, languages in favourite_languages.items():
print(f"\n{name.title()}'s favourite languages are:")
for language in languages:
print(f"\t{language.title()}")

Which variable holds the language list for each person? As you step over
the favourite_languages dict, using:

for name, languages in favourite_languages.items()

the person’s name is in the variable “name” and the list of their
favourite languages is in the variable “languages”.

So you need to check the length of the languages variable:

if len(languages) == 1:
    # Only one language, use singular form.
    print(...)
else:
    # Two or more languages, use plural form.
    print(...)

I found this post due to me having the same issue. This is mentioned in Python Crash Course (3rd edition) page 109.

The other user helped me so many thanks to Steven.

Here’s my code which seems to work, perhaps someone could leave feedback if its wrong or there’s an easier way:

favourite_languages = {
    'jen': ['python', 'rust'],
    'sarah': ['c'],
    'edward': ['rust', 'go'],
    'phil': ['python', 'haskell']
    }

for name, languages in favourite_languages.items():
    if len(languages) == 1:
        print (f"\n{name.title()} favourite language is:")
        for language in languages:
            print (f"\t{language.title()}")
    else:
        print (f"\n{name.title()} favourite languages are:")
        for language in languages:
            print (f"\t{language.title()}")

That looks OK.

It could be made slightly shorter, though.

The 2 branches of the if statement end with the same for loop, so that could be moved out of the if statement like this:

for name, languages in favourite_languages.items():
    if len(languages) == 1:
        print (f"\n{name.title()} favourite language is:")
    else:
        print (f"\n{name.title()} favourite languages are:")

    for language in languages:
        print (f"\t{language.title()}")
1 Like

Thanks Matthew for the help

Ooh we code golfin’? :sweat_smile:

favourite_languages = {
    'jen': ['python', 'rust'],
    'sarah': ['c'],
    'edward': ['rust', 'go'],
    'phil': ['python', 'haskell'],
    'bob': []
}

for name, languages in favourite_languages.items():
    # requires python >= 3.10
    match len(languages):
        case 1: golf = " is"
        case _: golf = "s are"

    print(
        f"\n{name.title()}'s favourite language{golf}:",
        *map(str.title, languages or ["None :("]),
        sep="\n\t",
    )

There are shorter ways than a match statement:

golf = " is" if len(languages) == 1 else "s are"

golf = {1: " is"}.get(len(languages), "s are")

golf = ["s are", " is"][len(languages) == 1]

:slight_smile:

Can also save a couple characters by spelling it “favorite” :joy:

1 Like

Now you’re being silly! :slight_smile:

:joy: I wanted to spell it as ‘favorite’ however I couldn’t betray my fellow brits

English Golf, the latest in data compression techniques. Drop all the unnecessary letters!

1 Like

:3

" is" if len(l)==1 else"s are"
{1:" is"}.get(len(l),"s are")
["s are"," is"][len(l)==1]
's  iasr e'[len(l)==1::2]
's  iasr e'[len(l)<2::2]

Yet another way:

favourite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
}


for name, languages in favourite_languages.items():
    print(f"\n{name.title()}'s favourite",
          'language is' if len(languages) == 1 else 'languages are')
    for language in languages:
        print(f"\t{language.title()}")