Writing a number in a list, IndexError: list assignment index out of range

Question:

I would like to write a number in a list but this number comes from a variable. Indeed, I am reading packets and I am getting back the IP addresses. My list is first filled with 0 and when I got an IP address, I will put the end of the IP address at the right case at 1. And I want to count the number of 1 in the list.
For example (I don’t know the IP adresses) :

Mydico=[]
for i in range(len(Mydico)):
    Mydico[i]=0
IP_address = '192.168.1.25'
nber=IP_address.split('.')[-1]# I got 25 in the variable nbre
Mydico[int(nber)]=1
print Mydico.count(1)

I got the following error :
Mydico [int(nber)]=1
IndexError: list assignment index out of range

Edit : I did many changes because I mistook dictionaries and lists

Asked By: DjibTgy

||

Answers:

IP_adress is a string here as you can use split on it. However if you want to index a list you have to give a number. So you’ll need to cast it to integer

List[int(nbre)]=1

Usually using the name List (even if it’s better than list which is a builtin) as a variable is not really a good practice.

Edit:
As OP changed his post to make appear MyList i will add some information.

First Mylist = {} create a dictionnary not a list. If you want to use a dictionnary you could use string as a key, and don’t really need to convert to int. If you don’t know what is a dictionnary I let you read section 5.5

If you need to initialize an empty list you must do Mylist = []. If you want to add item to the list you must do Mylist.append(foo). However if you do that you will add one number at a time.

Answered By: Peni

In your code

Mydico=[]
for i in range(len(Mydico)):
    Mydico[i]=0

len(mydico) will be zero. So your Mydico remains [].

and

IP_address = '192.168.1.25'
nber=IP_address.split('.')[-1]# I got 25 in the variable nbre
Mydico[int(nber)]=1

int(nber) is 25. you can not change mydico[25] because you don’t have list that long.

Answered By: surya singh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.