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.
-
You should verily read How to Ask. Your question history is quite bad. Read this article by the mighty Jon Skeet: Writing the perfect question. Finally, you should accept the answer if it was helpful to you.Sнаđошƒаӽ– Sнаđошƒаӽ2016-05-07 13:52:10 +00:00Commented May 7, 2016 at 13:52
Add a comment
|
1 Answer
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