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
Use insert
.
a = int(input())
l1 = []
for i in range(a):
l1.insert(999999999999,5)
print(l1)
Executing:
10
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
You are referring to the i
-th element, but your list is empty. It has to have a i
-th element to write a[i] = 5
. So, populate your list with a dummy value. eg, start with l1 = [None] * a
instead of l1 = []
.
You 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.