-3

I've been far from python for a while. when I try bellow code it gives me Index Error

n = int(input())
array = []
for i in range(n):
    array[i] = i+1
Harsh Bhut
  • 238
  • 2
  • 14
  • 1
    Are you trying to append values to the array? (P.S.: It's actually a list, not an array) – Aran-Fey Apr 24 '18 at 11:59
  • 2
    try `array.append(i+1)` – Rakesh Apr 24 '18 at 12:00
  • It's a list, you add value to the list with the append method. If you call array[i], the element i must exist in the list, else you get an Index Error. – Mathieu Apr 24 '18 at 12:01
  • Possible duplicate of [Quickly append value to a list](https://stackoverflow.com/questions/10215292/quickly-append-value-to-a-list) – Aran-Fey Apr 24 '18 at 12:05
  • 1
    [How to create a list of numbers](https://stackoverflow.com/questions/29558007/how-can-i-generate-a-list-of-consecutive-numbers) – Aran-Fey Apr 24 '18 at 12:06

3 Answers3

2

Use append method:

n = int(input())
array = []
for i in range(n):
    array.append(i+1)

Your error appears because you are calling array[0] which doesn't exist and trying to assign value to it.

zipa
  • 27,316
  • 6
  • 40
  • 58
  • [Please don't answer obvious duplicates.](https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled) – Aran-Fey Apr 24 '18 at 12:03
1

If you decide to create a list, then you should append elements to your list:

myList = list()
list.append(element)

You can also create a dictionary where you can index elements:

myDict = dict()
mydict[i] = element
Ctrl S
  • 1,053
  • 12
  • 31
Val Berthe
  • 1,899
  • 1
  • 18
  • 33
0

I made an obvious mistake because I'm learning C right know. in C you can do it in this way:

for (i = 0; i < n; i++)
{
    array [i] = i+1
}

but in python you must put your element you want to insert inside a bracket:

for i in range(n):
    array += [i+1]