I am currently learning python, i honestly quite like it, but it’s a very odd language!
In almost every other loose typed language you can initialise an array as follows (i know python calls them lists for some reason), so in php for example:
$array = [];
$array[0] = 1;
$array[1] = 2;
But when i try the same in python:
array = []
array[0] = 1
array[1] = 2
I get the following error:
IndexError: list assignment index out of range
So this says to be the elements need initialising like you would in languages like C, i’m just asking is there a quick way to initialise all the elements? For example in php we have the array_fill() function
I have also tried something like this:
array = [int]*10
array[0] = 1
but my ide is showing me this:
Unexpected type(s): (int, int) Possible type(s): (SupportsIndex,
Type[int]) (slice, Iterable[Type[int]])
EDIT
This one works:
a = [0] * 10
a[0] = 20
BUT i ran into a new problem, i actually want to store an object in there. Here is an example:
class MyTest:
id: int = 1
myObj = MyTest()
a = [0] * 10
a[0] = myObj
This is giving a type error again. All i want to do is store the object in a specific location in the array.
>Solution :
Direct assignment:
array = [1, 2, 0, 0, 0, 0, 0, 0, 0, 0]
Multiplication initialisation:
array = [0] * 10
array[0] = 1
array[1] = 2
List by comprehension:
array = [i+1 if i<2 else 0 for i in range(10)]
Append:
array = []
array.append(1)
array.append(2)
for i in range(10-2):
array.append(0)
Insert:
array = []
for i in range(10-2):
array.insert(0, 0)
array.insert(0, 2)
array.insert(0, 1)