-1

I want to create a 2d vector in python and later add elements to it accordingly. I should also be able to retrieve the size of the vector in my code.

Ankit Basarkar
  • 1,239
  • 3
  • 12
  • 13
  • You should verily read [ask]. Your question history is quite bad. Read this article by *the mighty* [Jon Skeet](http://meta.stackexchange.com/questions/9134/jon-skeet-facts): [Writing the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Finally, you should [accept](http://stackoverflow.com/help/accepted-answer) the answer if it was helpful to you. – Sнаđошƒаӽ May 07 '16 at 13:52

1 Answers1

2

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
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90