Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i create array/list keys in python?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading