-2

I want to make a 2D array (not list) from 2 given lists. How would I do that? For example, I want to generate a 2D 2by5 array with the list [1,2,3,4,5] and [6,7,5,9,34] And also how would I iterate that array. I have tried this

#import the necessary module
import array as arr

list1 = [2,3,5,7,1]
list2 = [13,17,19,23,29]

myarr = arr.array('i')
index = 0
for i in list1:
    myarr[0][index] = i
    index = index+1
index = 0
for i in list2:
    myarr[1][index] = i
    index = index+1

print(myarr)

Got the error

Traceback (most recent call last):
  File "temp.py", line 10, in <module>
    myarr[0][index] = i
IndexError: array index out of range
5
  • Does this answer your question? 2D arrays in Python Commented Sep 30, 2020 at 14:45
  • 2
    using numpy? .. Commented Sep 30, 2020 at 14:45
  • 1
    the array module does not support multidimensional arrays. Commented Sep 30, 2020 at 14:46
  • No unfortunately that does not Commented Sep 30, 2020 at 14:48
  • 1
    If you can't use numpy, then why must you use the array module? Commented Sep 30, 2020 at 14:56

2 Answers 2

0

from the documentation of the array module:

This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained.

So, and array is 1D, and you can't have an array of arrays like you can have list of lists. 2D arrays are not possible. As others have said: Numpy will be your friend here.

Sign up to request clarification or add additional context in comments.

Comments

-1

Take an empty array first and take inner array as integer array
And then append values as follows

#import the necessary module
import array as arr

list1 = [2,3,5,7,1]
list2 = [13,17,19,23,29]

myarr = []

myarr.insert(0, arr.array('i'))
for i in list1:
    myarr[0].append(i)

myarr.insert(1, arr.array('i'))
for i in list2:
    myarr[1].append(i)

print(myarr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.