a = int(input())
l1 = []
for i in range(a):
l1[i] = 5
print(l1)
I keep getting the error:
list assignment index out of range
i will always be smaller than a so why am I getting this error? I don't wish to use append().
You could use this if you want to get a list of n '5' elements:
a = int(input())
l1 = [5 for _ in range(a)]
print l1
It will wait for input and save the list in the l1 list
i by _ since it's not being used hereYou might be confusing the behavior of list to dictionary. Dictionary would work.
a = int(input())
l1 = {}
for i in range(a):
l1[i] = 5
print([j for i,j in l1.items()])
You got an error because there exists no element at l1[0] to be assigned users input. If we were to make your code work, we need to pre-populate the list with dummies.
a = int(input())
l1 = (','*(a-1)).split(',')
for i in range(a):
l1[i] = 5
print(l1)
It seems to me that the simplest change is to append the elements, rather than use an index. The list doesn't need to be pre-sized and the code is easy to read for someone coming from another language. Replace "i" with "_" if you like.
a = int(input())
l1 = []
for i in range(a):
l1.append(5)
print(l1)
l1has length zero, so you cant index intol[i]for anyi. Why you don't want to useappendis beyond me.append()is the one obvious way to do it. Using anything else would make for worse code.l1 = [5 for _ in range(10)]andprint (l1)if you are so against theappend().