Page 1 of 1

How do I create and use integer array?

Posted: Sat Jan 23, 2021 7:12 pm
by MicroGuy
<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>

Re: How do I create and use integer array?

Posted: Sat Jan 23, 2021 7:43 pm
by dhylands
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])
>>>

Re: How do I create and use integer array?

Posted: Sat Jan 23, 2021 9:35 pm
by mikesmith
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]

Re: How do I create and use integer array?

Posted: Sun Jan 24, 2021 4:12 am
by dhylands
A list also consumes considerably more memory than an array.

Re: How do I create and use integer array?

Posted: Wed Sep 22, 2021 4:12 pm
by bradstew
To create an integer array with a fixed length.
x=array.array('i',[0]*10)
This seems to create an array of 10 ints with zero initialization.
Very handy!

Re: How do I create and use integer array?

Posted: Thu Sep 23, 2021 8:54 am
by pythoncoder
I think

Code: Select all

x = array.array('i', (0 for _ in range(10)))
is more efficient, especially if the array is large. That is because [0]*10 creates a list which involves allocation.