3
for i in range(5):
    mylist[i]=int(input("Input an integer: "))

Do I really still have to define mylist before the for loop before I can actually use it? At the first loop it works fine but at the second loop it will show a NameError do I have to use a different inut method or what?

NameError: name 'mylist' is not defined

4
  • 1
    Yes, you cannot index a variable that doesn't exist. Declare mylist ahead of the loop or you'll get IndexError and NameError problems Commented Oct 14, 2020 at 16:46
  • Hello And Welcome to StackOverflow Please show your full Commented Oct 14, 2020 at 16:47
  • Unless there's more code that you're not showing, it doesn't make sense to try to set or get something at an index of a list that has yet to be defined. Commented Oct 14, 2020 at 16:47
  • check out my answer Commented Oct 14, 2020 at 16:57

5 Answers 5

2

Yes, you need to define what "mylist" is before you assign values to it.

mylist = []
for i in range(5):
    mylist.append(int(input("Input an integer: ")))
Sign up to request clarification or add additional context in comments.

2 Comments

This will throw an IndexError - set the size beforehand, i.e. mylist = [None] * 5
use append method to add anything to list.
0

Yes, you have to define the list before like this

mylist=[]
for i in range(5):
    mylist[i]=int(input("Input an integer: "))

1 Comment

As pointed out on TimTam's answer, this will throw an IndexError unless the size of the list is declared beforehand. This can be circumvented by using .append(), though
0

you could just use list comprehension

mylist = [int(input("Input an integer: ")) for _ in range(5)]

Comments

0

You need to define mylist before you assign values to it.

mylist = [1, 2, 3, 4, 5]
for i in range(5):
    mylist[i]=int(input("Input an integer: "))

Or if you want to fill the empty list use append() list function

mylist = []
for i in range(5):
    mylist.append(input("Input an integer: "))

Comments

0

yes you are needed to define the list before the loop and also define the contents too, because it will throw a error Note: here i used 0 you can also use keyword None

myList = [0, 0, 0, 0, 0]
for i in range(5):
    myList[i] = int(input("Enter a int: "))

or you could also use function append using this you don't have to define what does myList contains-

myList = []
for i in range(5):
    myList.append(int(input("Enter a int: ")))

Comments

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.