haroldmk
haroldmk

Reputation: 1

Retrieve the names of the object of a list in Python

I have a list of vectors

vector1=[1,1]
vector2=[2,2]
favoritevector=[1,-1]

Then a list of those vectors

vectors=[]
vectors.append(vector1)
vectors.append(vector2)
vectors.append(favoritevector)

vector
>>vector = [[1,1], [2,2], [1,-1]]

How can I retrieve the names of the objects inside the list vectors, instead of the actual value of the objects.

In this case, I would like to something that if I ask for the element 0 of the list vectors the function or command returns to me the name "vector1" instead of [1,-1].

Thanks in advance for the help.

Upvotes: 0

Views: 441

Answers (2)

vonBerg
vonBerg

Reputation: 154

If the order of the vectors is not important you can use dictionaries

vectors_dict["vector1"] = [1, 1]

Upvotes: 0

oliver2213
oliver2213

Reputation: 141

I don't think there is a way to do this using a list. You might try something like this:

class vector(object):
    def __init__(self, name, x, y):
        self.name = name
        self.x = x
        self.y = y

    def __repr__(self):
        return """<vector {} {}>""".format(self.name, (self.x, self.y))

Then, you can do:

vectors = []
vectors.append(vector(name="vector1", x=1, y=2))
vectors.append(vector(name="vector2", x=2, y=3))
# to get the name of the first vector, do:
vectors[0].name
# 'vector1'

Upvotes: 1

Related Questions