Home > Back-end >  How define jagged array in python
How define jagged array in python

Time:06-24

Jagged array : A multidimensional array that has lines of varying length I also use C # cinnamon tooth arrays in Python. Is it possible?

int[][] jaggedArray = new int[3][];

jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2];

CodePudding user response:

Just have a 2d array and fill it with zeros

jaggedArray = [[] for row in range(3)]
'''
above line same as
jaggedArray = []
for row in range(3):
    jaggedArray.append([])
'''
jaggedArray[0] = [0]*5
jaggedArray[1] = [0]*4
jaggedArray[2] = [0]*2
print(jaggedArray)

CodePudding user response:

You can do something like this:

jaggedArray=list()
jaggedArray.append([0]*5)
jaggedArray.append([0]*4)
jaggedArray.append([0]*2)

This will create similar array that you have created in sample code.

CodePudding user response:

you can use a mutable data type for this, ie list

just create a list, define it's size if you want list_ = [None for i in range(4)]

and then with index you can add sublist inside it of any length like

list_[1] = [1,2,3,4,]
# list_ = [None, [1,2,3,4], None, None]

or you can create an empty list list_ =[] and add the sublist using append operation like

list_.append([1,2,3])
#list_ = [[1,2,3]]

in later stage if you want to overwrite the sublist, you can directly do that by assigning the index to new sublist ie list_[2] = [1,2,3,]

  • Related