0

I want to know why I cant access a list index. I have a list full of words(input) but then t try to acces for example: list[2] and I get an error.

words=[]
n =input().split()
words.append(n)
print (words])

Intput: Hi internet what up Output: [['hello', 'internet', 'what', 'up']]

print(words[0])

Output:['hello', 'internet', 'what', 'up']

print(words[1])

Output: IndexError: list index out of range

  • lol, not a duplicate; one would have to already know the difference (not to mention the very existence of `extend`) in order to not run into this bug – necromancer Jan 19 '18 at 01:01
  • Fundamental misunderstanding: "I have a list full of words(input)". You do not. You have a list, which *contains a single element*, which happens to be another list, which contains the word strings. – juanpa.arrivillaga Jan 19 '18 at 01:17

1 Answers1

2

use extend not append; append appends a single element whereas extend appends all elemnets of a given list

necromancer
  • 23,916
  • 22
  • 68
  • 115
  • Thank you very much!! Do you know how to extend words in a list separated by " " but with a for, so let say-> for i in range 2: list.extend(input) input=hey what up output=[hey,what] – Alejandro Alcaraz Gonzalez Jan 19 '18 at 01:02
  • @AlejandroAlcarazGonzalez you don't. `.extend` avoids a for loop, but you could always do `for word in input().split(): words.append(word)` – juanpa.arrivillaga Jan 19 '18 at 01:16
  • @AlejandroAlcarazGonzalez words separated by `" "` are NOT A LIST! they are one single string. when you call `split()` the one single string is broken into many strings based on the `" "` separator. So, that's when you have a list of words and all the `" "` have been removed. In your question, you do not need 4 lines. You just need 1 line: `words = input().split()` and may be another line `print(words)` or `print(words[1])` depending on what you want to do. You only need extend if you need to read ANOTHER INPUT, then you do: `words.extend(input().split())` Lists and strings are DIFFERENT. – necromancer Jan 19 '18 at 09:47