-1

the thing that I am supposed to do is,

  1. get 10 int
  2. find the different value after doing %42 for those 10 input int

and what I thought is, like this

    n = []
    for i in range(10):
        a = int(input())
        n[i] = a%42
    s = set(n)
    print(len(s))

but it didn't work with a message of

----> 4     n[i] = a%42

IndexError: list assignment index out of range

and by googling I have solved this question by adding append.

n = []
for i in range(10):
    a = int(input())
    print("a",a)
    b = a%42
    print("b",b)
    n.append(b)
    
s = set(n)
print(len(s))

** here is my question. why did my code didn't work? I thought my method's logic is solid. Is there some knowledge that I am missing about? **

thank you previously.

danny lee
  • 61
  • 1
  • 1
  • 7
  • 1
    n is empty, use np.append – Dani Mesejo Oct 06 '21 at 07:19
  • 1
    use: `n.append(a%42)` – mozway Oct 06 '21 at 07:19
  • 1
    alternatively, initialize n with the final length: `n = [0]*10` – mozway Oct 06 '21 at 07:20
  • 1
    You are trying to assign data to a list index that doesn't exists. If you want to do it the way you tried earlier, you have to create a list with the appropriate length with something like `n = [None] * 10` – Tzane Oct 06 '21 at 07:21
  • 1
    Yes, you did something wrong, that's why there was an error. You can't make a list longer by just trying to set a value at an index that's out of bounds. – jonrsharpe Oct 06 '21 at 07:21
  • thank you all very much I have learned that "I have not set index which can be handled by setting the length of the list" thanks to everybody. – danny lee Oct 06 '21 at 07:33

2 Answers2

1

actually when you were trying first way you were using lists built-in dunder(magic method) which asks that there must be an element at that index before changing its value, meanwhile list is empty and hence it can't find an element whose value has to be chanced but append works something like this:

yourList += [newElement]

which is basically like list concatination.

Kunal Sharma
  • 416
  • 3
  • 12
0

Your code doesn't work because n is an empty list so it has no sense to assign a value to an index. If you know the size of your list you can do:

# this works
n = [size]
n[0] = 1
  • What you have given as an answer is true within the context of your code. But it's misleading. Try adding *n[1]=1* to your code and see what happens –  Oct 06 '21 at 07:31