-2
name1=input("Give 1st name: ")
name2=input("Give 2nd name: ")
name3=input("Give 3rd name: ")
names = [name1, name2, name3]
names = list(set(names))
names.sort()
print("names in alphabetical order: {}, {} and {}".format(*nimet))

My code gives error: tuple index out of range when 2 names are same. When inputs are like Ava, Benjamin and Charlie, I want the output to be like: names in alphabetical order: Ava, Benjamin and Charlie but when inputs are like Ava, Benjamin, Ava, I want the output to be like: names in alphabetical order: Ava and Benjamin

Arttu
  • 9
  • 1

3 Answers3

0

Set makes elements unique(removes duplicate). The error Tuple index out of range which you are getting is because in your print line you are expecting 3 elements but your tuple has just two because the duplicate element has been removed. So the error says tuple index out of range. So in such scenarios if you want to use set and don't know the number of elements in a tuple, the best bet would be to use joins.

[Edit with code snippet which would work]:

name1=input("Give 1st name: ")
name2=input("Give 2nd name: ")
name3=input("Give 3rd name: ")
names = [name1, name2, name3]
names = list(set(names))
names.sort()
print("names in alphabetical order are:"+ ",".join(str(e) for e in names))
E_net4
  • 27,810
  • 13
  • 101
  • 139
mozilla-firefox
  • 864
  • 1
  • 15
  • 23
0

the number of arguments of .format() must match the number of {}-s in the string you are formatting.

You can deal with this before the .format():

name1=input("Give 1st name: ")
name2=input("Give 2nd name: ")
name3=input("Give 3rd name: ")
names = [name1, name2, name3]
names = list(set(names))
names.sort()

first_names = ', '.join(names[:-1])

print("names in alphabetical order: {} and {}".format(first_names, names[-1]))
ishefi
  • 480
  • 4
  • 12
0

You can use ', '.join to join the names together with commas in between. But you also want "and" between the last two names instead of a comma. One solution is to join the last two names with "and" first, and then join the rest with commas.

def join_names(names):
    names = sorted(set(names))
    if len(names) > 1:
        last, second_last = names.pop(), names.pop()
        names.append(second_last + ' and ' + last)
    return ', '.join(names)

Examples:

>>> join_names(['Alice', 'Bob', 'Clive'])
'Alice, Bob and Clive'
>>> join_names(['Clive', 'Bob', 'Clive'])
'Bob and Clive'
>>> join_names(['Alice', 'Alice', 'Alice'])
'Alice'
>>> join_names(['John', 'Paul', 'George', 'Ringo'])
'George, John, Paul and Ringo'
kaya3
  • 47,440
  • 4
  • 68
  • 97