1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Kagamine Len
  • 121
  • 4
  • 1
    you're _appending_ the result of `x.split` to your list. You probably intend to _extend_ list: https://stackoverflow.com/a/252711/1810460 – Hamms Jun 13 '17 at 00:13

4 Answers4

3

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
idjaw
  • 25,487
  • 7
  • 64
  • 83
1

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])
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • My question is that is there a way to get the 3rd word directly from a list? So like I place my sentence " I like candy" into the program and it puts it in the list. Is there a way to get the string 'candy' from my list? – Kagamine Len Jun 13 '17 at 00:19
  • Yes, you can extend the the value from the split function into an empty list. Keep in mind, however, that split itself does create a list. Please see my recent edit. – Ajax1234 Jun 13 '17 at 00:22
0

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.

Programah
  • 179
  • 1
  • 10
0

split() in python returns the list. So you are just appending the list into your list L. Instead do L=x.split(' ')

deepakchethan
  • 5,240
  • 1
  • 23
  • 33