If you want to create an empty array (or list because there are no arrays in Python), you can use this line of code:
1 |
myarray = [] |
After you do this, you can append elements to this list.
1 2 3 4 5 6 |
myarray = [] myarray.append(5) myarray.append('z') print(myarray) |
If you want to create an equivalent of an array from the C/C++ language, you can declare an array as None and multiply it by the number of values.
1 |
a = [None] * 4 |
Let’s see, how Python treats this declaration. Let’s run this code:
1 2 |
myarray = [None] * 4 print(myarray) |
This is the result:
[None, None, None, None]
You have a list with 4 None values. You can assign a new value to each element by specifying an index of the array.
1 2 3 4 5 6 |
myarray = [None] * 4 myarray[1] = 5 myarray[3] = 'z' print(myarray) |
Run the code.
[None, 5, None, 'z']
Notice that two values changed, at positions 0 and 2.