0

Hello so im new on python, i want to know how to do multiple string input on list. I already try to append the input to the list, but it doesn't give me expected output. Here is the source code:

test=[]
input1=input("Enter multiple strings: ")
splitinput1=input1.split()
for x in range(len(splitinput1)):
    test.append(splitinput1)
print(test)
print(len(test))

And the output is not what i expected:

Enter multiple strings:  A B C
[['A', 'B', 'C'], ['A', 'B', 'C'], ['A', 'B', 'C']]
3

However, when i change to print(splitinput1), it give me expected output:

Enter multiple strings:  A B C
['A', 'B', 'C']
3

So how to make the output like print(splitinput1) while use print(test) and whats missing on my code? Thankyou.

2
  • 2
    You're doing a lot of extra steps and duplicating the list unintentionally with that for loop. Just do test = input("Enter multiple strings: ").split(). Commented Oct 25, 2022 at 14:08
  • 1
    If you really want to play with for loops, the code you want is for x in splitinput1: test.append(x). You don't want to append all of splitinput1 to test three times, you want to append each of the three items individually. (This for loop is also the same as test.extend(splitinput1).) Commented Oct 25, 2022 at 14:10

2 Answers 2

1

You have slight error in your code. Do this:

test=[]
input1=input("Enter multiple strings: ")
splitinput1=input1.split()
for x in splitinput1:
   test.append(x)
print(test)
print(len(test))
Sign up to request clarification or add additional context in comments.

1 Comment

no need for the for loop
1
strings = input("Enter multiple strings: ")
test = strings.split()
print(test)
print(len(test))

2 Comments

Your solution for the ['A', 'B', 'C'] is right sir, but the print(len(test)) shows 1. So when i want to print(test[2]) it give me IndexError: list index out of range. So @BishwashK is more correct
test.append(strings.split()) creates a list inside a list => [['a', 'b', 'c']]. so len() gives a result of 1. better to use: test = strings.split(). this also makes the first line of the code redundant: remove test = []. then the length of the list will be given correctly.

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.