Reputation: 121
So my program here is supposed to take in a sentence, and then spit out the third word.
Here is my code below:
L = []
x = input('Enter a sentence: ')
L.append(x.split(' '))
print (L[2])
For some reason I get the error: IndexError: list index out of range
.
Upvotes: 1
Views: 60
Reputation: 26610
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])
Enter a sentence: chicken goes bock
bock
Upvotes: 3
Reputation: 167
Try this:
x = input("Enter a sentence:");
x.split(' ');
print (x[2])
string.split(x);
Will turn the output into an array, no need for using append.
If you want to append this value to an array now, just do array[a] = x[b]
, where a and b are integers.
Upvotes: 0
Reputation: 71471
You are adding a list, created when you split the sentence, to a list. Thus, you have a final list with only one element, the list. Try this:
x = input('Enter a sentence: ')
l = []
l.extend(x.split())
print(new_list[2])
Upvotes: 1
Reputation: 5600
split() in python returns the list. So you are just appending the list into your list L. Instead do L=x.split(' ')
Upvotes: 0