If you actually print out the value of L
after you perform this:
L.append(x.split(' '))
You will see you actually created a list of lists, which is definitely not what you want. Running your code with a sample input "chicken bock", yields:
[['chicken', 'bock']]
What you want to do is simply assign the result of split
to L
L = x.split(' ')
Furthermore, you need to pay attention as to how many elements you enter in your sentence. Especially since lists start at index 0, you need to make sure you actually access an index within the bounds. So if we take the example of "chicken bock" as input, your test of L[2]
, will not work. You would actually need L[1]
to get the second element of the list.
Finally, if for whatever reason you are still looking to "add" elements to your list L
, then based on the solution you have worked out, you actually want to use extend
and not append
:
L.extend(x.split(' '))
A practical example that provides the third element:
L = []
x = input('Enter a sentence: ')
L = x.split(' ')
print(L[2])
Output:
Enter a sentence: chicken goes bock
bock