Home > Net >  did I did something wrong with list and for loop in python? [duplicate]
did I did something wrong with list and for loop in python? [duplicate]

Time:10-06

the thing that I am supposed to do is,

  1. get 10 int
  2. find the different value after doing B 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.

CodePudding user response:

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.

CodePudding user response:

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
  • Related