0

I have an array of points and I'm looking to print the name of the points instead of the actual points.

A = (2,0)

B = (3, 4)

C = (5, 6)

array1 = [A, B, C]

when I do print(array1[0]) it ends up printing the values. But I want to print the letters such as A, B or C. How would I print the letters instead?

I've also tried print(array1) and it also just prints all the values instead.

Jimpsoni
  • 233
  • 2
  • 13

2 Answers2

1

A variable doesn't usually contain its own name. This is simply something you can use to target whatever value that is being referenced.

Obviously, the best answer will be related to the really why you want to print "A". If you just want to print the letter "A", then simply do:

print("A")

Obviously, that doesn't scale well depending on the reason why you want to print the name of the variable.

Instead, why don't you use a dictionary? A dictionary is a structure that contains a list of keys that each reference a different value.

dictionary = {"A": (2, 0), "B": (3, 4), "C": (5, 6)}

You can reference each tuple by using the key instead of an index.

print(dictionary["A"])

Will return (2,0)

If you want to print the first value of "B", you simply do dictionary["A"][0].

Alright, now, for the good stuff. Let's say that you want to print all keys AND their values together, you can use the items() method like this:

for key, value in dictionary.items():
  print(f"{key}={value}")

What happens if that items() will return a generator of tuples that contains both the keys and their corresponding value. In this way, you And you can use both the key and the value to do whatever you want with them.

By the way, the f in front of the string tells python that this is a formatted string and will compute anything written in between curly brackets and include them as part of the string. In this case, the code written above will output the following:

A=(2,0)
B=(3,4)
C=(5,6)
0

Try writing array1=["A", "B", "C"] instead of array1=[A, B, C]. A, B, and C are variables so they represent their value, if you want the letters A, B, and C you should use strings instead.

  • That makes sense, but I need to maintain the values because I have to put the array into a function called get_closest_points(). This function should return distance and the name of the 2 points. I can get the distance fine, but I have no idea how to get and concatenate the letters. – CloudNguyen Nov 13 '22 at 18:58
  • @CloudNguyen that information was missing in your question. In your question you just tried to access by index. Sounds like you might want to create objects that store both their names and their points. – Dan Getz Nov 13 '22 at 19:07