-1

I know how to make an empty list, for example:

a = []

Also, to make the list of size 4, I can use * size, for example:

a = [None] * 4

But, why do I have to use None?

I've been trying to use a = [] * size, but it's failing.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Jin
  • 11
  • 1

3 Answers3

4

The List in Python is not an Array of fixed-size upon declaration, so it is by design variable in size. Meaning you can just append members into it. Much like ArrayLists in Java!

So if the context of your question(I am just guessing here) is to find ways to limit the size of a particular List in Python, you would have to do it elsewhere, not during declaration.

Useful reference for this topic: https://www.delftstack.com/howto/python/python-initialize-empty-list/

xhbear
  • 41
  • 4
3

How can I make an empty list of size 4 in python?

You must not, as these are mutually exclusive requirements: to have list which is empty (i.e. has size 0) and has size 4

Daweo
  • 31,313
  • 3
  • 12
  • 25
0

You can't make an empty list of length n because the result will be an empty list []. This behavior is caused by the value you insert into the list when you apply the []*n technique, so if you don't put anything inside the list, it won't create any nodes to hold information. Instead, you need to insert a None value in order to force the list to create nodes with empty values as if it were an array with null cells.

As Python lists work as linked lists, I suggest you take a look at some documentation about data structures and algorithms to better understand the meaning of nodes that hold information:

a = [None]*4
print(a)

Output:

[None, None, None, None]
Cardstdani
  • 4,999
  • 3
  • 12
  • 31