How do I create and use integer array?

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
MicroGuy
Posts: 4
Joined: Sun Jan 17, 2021 8:31 pm

How do I create and use integer array?

Post by MicroGuy » Sat Jan 23, 2021 7:12 pm

<r>I'd like to know how to set up an array of integers for a micro:bit MicroPython project. The program needs to establish a 10-value array of signed integers and later read values from and put values in this array. I have read the MicroPython documentation, for example: <URL url="http://docs.micropython.org/en/v1.9.3/p ... <LINK_TEXT text="http://docs.micropython.org/en/v1.9.3/p ... ml#classes">http://docs.micropython.org/en/v1.9.3/p ... TEXT></URL>. As a newcomer to Python and MicroPython, it's unintelligible without a few concrete examples that show how to create and use an array. I couldn't find an elementary example in the Forum or online. Could someone provide or point me to examples? All help is greatly appreciated. Thank you. --Jon</r>

User avatar
dhylands
Posts: 3587
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: How do I create and use integer array?

Post by dhylands » Sat Jan 23, 2021 7:43 pm

The documentation for python's array module can be found here: https://docs.python.org/3/library/array.html

Using that I was able to do the following on my pyboard:

Code: Select all

>>> import array
>>> x = array.array('i', [11, 22, 33, 44, 55])
>>> x
array('i', [11, 22, 33, 44, 55])
>>> x[0]
11
>>> x[1]
22
>>> x[2] = 333
>>> x
array('i', [11, 22, 333, 44, 55])
>>>

mikesmith
Posts: 1
Joined: Sat Jan 23, 2021 7:27 pm

Re: How do I create and use integer array?

Post by mikesmith » Sat Jan 23, 2021 9:35 pm

It can be as simple as:

Code: Select all

numbers = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Pedantically, that's not an array - it's a list - but it's indexable and mutable in exactly the sort of ways that you care about.

Code: Select all

>>> numbers[7] = 11
>>> numbers[5] = 12
>>> numbers[3] = numbers[5] * 2
>>> print(numbers)
[0, 0, 0, 24, 0, 12, 0, 0, 0, 0]

User avatar
dhylands
Posts: 3587
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: How do I create and use integer array?

Post by dhylands » Sun Jan 24, 2021 4:12 am

A list also consumes considerably more memory than an array.

Post Reply