0

I have few arrays, in my code. I wanna be able to change, which I am using in one place, and to be able to print name of it only changing one line (definition).

Example:

XYZ=my_array #definition of which array I am using now I am calling only XYZ
#some_code
print('the name of array I am using is my_array')

Now I want to have in print being to able call XYZ array not my_array. So I don't have to change it twice, but It will show the same output.

How do I that?

Von
  • 35
  • 1
  • 6
  • I think he wants to print my_array, not XYZ – Colim Jul 08 '22 at 10:32
  • Something like this - `print(f'the name of array I am using is "XYZ": {XYZ} ')` It will print the var. name and its content (or you *can skip latter part*) – Daniel Hao Jul 08 '22 at 10:37
  • You're looking for this? [https://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python](https://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python) – Sau1707 Jul 08 '22 at 10:43
  • Yeah sort of @Sau1707 But the thing is I don't want to call my_array again. I want make XYZ ''remember'' of what array I am using. – Von Jul 08 '22 at 10:53

3 Answers3

0

To print an array in Python, use the print() function. The print() is a built-in Python function that takes the name of the array containing the values and prints it. To create an array in Python, use the numpy library and create an array using the np.array() function, and then print that array in the console.

import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(arr)

0

you can use a class to store the array and the name, then you can access with .name o .array

class Foo():
    def __init__(self, array, name):
        self.array = array
        self.name = name
        
my_array = [1,2,3,4]
XYZ=Foo(my_array, "name")

print(XYZ.array)
print(XYZ.name)
Sau1707
  • 69
  • 6
0

There are many ways to answer this question. This is one of the ways that i would do it.

You can store your list in a dict and assign a key(basically a unique name) to it and you can call it at your disposal when u want it.

_my_dict = {
"my_first_array" : [1,2,3],
"my_second_array" : [4,5,6],
}
# this is how to get all the names of the list
print(_my_dict.keys()) # ['my_first_array','my_second_array']
# this is how to access your list by name
print(_my_dict['my_first_array']) # [1,2,3]