0

I am trying to create a small program that prompts the user to input 3 words, then put the string inputs into an array, then sort the array lexicographically and print the array as a string list.

I have tried the .sort function which does not work. The project I am working on does not require knowledge of loops (which I do not have a lot of experience with yet).

    a = []
    first = input("Type a word: ")
    second = input("Type another word: ")
    third = input("Type the last word: ")
    a += first
    a += second
    a += third

    a = sorted(a)

    print(a)

I want the printed results to be the 3 words together separated by commas

 Apple, Banana, Egg

Instead, my code prints

 ['A', 'B', 'E', 'a', 'a', 'a', 'e', 'g', 'g', 'l', 'n', 'n', 'p', 'p']

3 Answers 3

2

The problem is that += on a list is the concatenation of two lists.. and so python interprets your string "Apple" as the (unpacked) list ['A', 'p', 'p', 'l', 'e'] .

Two different solutions:

1) Make the inputs a single list with the word:

a = []
first = input("Type a word: ")
second = input("Type another word: ")
third = input("Type the last word: ")
a += [first]
a += [second]
a += [third]

a = sorted(a)

print(a)

or

2) simply use the append method, which expects a single element.

a = []
first = input("Type a word: ")
second = input("Type another word: ")
third = input("Type the last word: ")
a.append(first)
a.append(second)
a.append(third)

a = sorted(a)

print(a)
Sign up to request clarification or add additional context in comments.

Comments

0

The best way to add to a list is by using .append

In your case I would just do:

a = []

first = input("Type a word: ")
second = input("Type another word: ")
third = input("Type the last word: ")

a.append(first)
a.append(second)
a.append(third)

print(sorted(a))

Once your done adding the numbers to your array (called a list in python) just use the sorted() method to lexicographically sort your words!

Comments

0

Rather than adding input words to the list, you should append it. When you add the string to the list, it will break the string down to each character and then will add it. Because you can't add one type of data to the another (Same as you can't add "1"+3, unless it's JS but it's complete different story).

So, you should append the words then use the {}.sort() method to sort the list and join it into a string.

a = []

first = input("Type a word: ")
second = input("Type another word: ")
third = input("Type the last word: ")

a.append(first)
a.append(second)
a.append(third)

a.sort()
finalString = ','.join(a)

print(finalString)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.