How to have an array of arrays in Python

33,523

Solution 1

From Microsoft documentation:

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes

Python documentation about Data Structures.

You could store a list inside another list or a dictionary that stores a list. Depending on how deep your arrays go, this might not be the best option.

numbersList = []

listofNumbers = [1,2,3]
secondListofNumbers = [4,5,6]

numbersList.append(listofNumbers)
numbersList.append(secondListofNumbers)

for number in numbersList:
    print(number) 

Solution 2

arr = [[]]

I'm not sure what you're trying to do, python lists is dynamically assigned, but if you want a predefined length and dimension use list comprehensions.

arr = [[0 for x in range(3)] for y in range(3)]

Share:
33,523
user6916458
Author by

user6916458

Updated on July 09, 2022

Comments

  • user6916458
    user6916458 almost 2 years

    I'm new to python, but I'm solid in coding in vb.net. I'm trying to hold numerical values in a jagged array; to do this in vb.net I would do the following:

    Dim jag(3)() as double
    For I = 0 to 3
       Redim jag(i)(length of this row)
    End
    

    Now, I know python doesn't use explicit declarations like this (maybe it can, but I don't know how!). I have tried something like this;

    a(0) = someOtherArray

    But that doesn't work - I get the error Can't assign to function call. Any advice on a smoother way to do this? I'd prefer to stay away from using a 2D matrix as the different elements of a (ie. a(0), a(1),...) are different lengths.

    • Cale
      Cale over 6 years
      a(0) = someOtherArray is trying to call a function called a and pass in 0 as an argument. The correct syntax would be a[0] = someOtherArray.
    • user6916458
      user6916458 over 6 years
      That is a carry over from vb.net! I need to unlearn so much! Thank you. I am now getting an error "Name 'a' is not defined"
    • Wildan Maulana Syahidillah
      Wildan Maulana Syahidillah over 6 years
      arr = [[]] I'm not sure what you're trying to do, python lists is dynamically assigned, but if you want a predefined length and dimension use list comprehensions.
    • user6916458
      user6916458 over 6 years
      That fixed It! Thank You!!
    • Cale
      Cale over 6 years
      a is just the name of whatever you called your array and [0] is the index. You'll need to define an array first before assigning values to it.
    • Wildan Maulana Syahidillah
      Wildan Maulana Syahidillah over 6 years
      arr = [[0 for x in range(3)] for y in range(3)]