0

I know how to declare an empty array of a certain size, say 25 lists in it -

mylist = [[] for _ in range(25)]

But if I don't know the size yet, how to define it? Obviously this following doesn't work -

mylist = [[] for _ in range(math.inf)] 

The reason I'm asking is that I need to assign value to some items in the list. For example -

mylist[1].append(87)

But it'll show an "index out of range" error if I simply declare an empty list in the beginning, i.e.

mylist = [[]]

I guess it's because I'm trying to access the second element, whereas even the first element doesn't exist yet.

Thank you in advance

Egret
  • 421
  • 1
  • 3
  • 13
  • Check this [post](https://stackoverflow.com/questions/5205575/how-do-i-get-an-empty-array-of-any-size-in-python). – marcdecline Sep 22 '20 at 06:49
  • Depends on the indices, you can either make a dict or dynamically append to the list when it's too small. Perhaps you already know how to do both of them? – user202729 Sep 22 '20 at 06:49
  • Thanks @user202729, seems the only solution is to dynamically append to the list when it's too small. I'm not sure how to do this though. Is the helper function suggested by Advay168 below the solution? – Egret Sep 22 '20 at 07:35

1 Answers1

1

Just append a new empty array if there is no array at that index:

mylist=[]

def insert_at(number,index,mylist):
    while index >= len(mylist):
       mylist.append([])
    mylist[index].append(number)

E.g.

insert_at(87,1,mylist)
Advay168
  • 607
  • 6
  • 10
  • Good idea! Though I wish there's a more "native" way in the language instead of having to define a helper function.. – Egret Sep 22 '20 at 07:36
  • It depends on your use case. There might be some other method to achieve what you want to do. – Advay168 Sep 22 '20 at 07:50
  • The closest "standard library" way would be to make the outer list into a dictionary; `mylist = collections.defaultdict(list)`; then you can use `mylist[index].append(number)` without checking whether or not the individual list exists. Obviously, the outer list is then a dictionary rather than a list, but it may fit better or worse for your particular use. – Jiří Baum Sep 22 '20 at 07:53
  • defaultdict is a good idea too! It seems defaultdict works more like a list than a dict.. – Egret Sep 22 '20 at 08:08