How to create a 2d vector in python

How to create a 2d vector in python

Use list of lists.

myL = []
for i in range(5):
   myL.append([i for i in range(5)])

for vector in myL:
    print(vector)

Output:

[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]

For every element of the list myL, you can get the length using len(myL[index]), and can also append element to it using myL[index].append(newelement). Example:

print(len(myL[2]))
# prints 5
myL[2].append(100)
print(len(myL[2]))
# prints 6

How to create a 2d vector in python

Leave a Reply

Your email address will not be published.