+ 2

Is there a way to print a list when you have its name as a string?

Say we have the list l= [1,2,3] and the string s= 'l'. Is there a way to get s to print l?

21st May 2021, 11:55 PM
Will
Will - avatar
10 Respostas
+ 6
it depends on in wich scope is the variable... if it's a global variable in the current module: print(global()[string_variable_name]) if it's a local variable: print(local()[string_variable_name]) if it's a variable in another module: import other_module print(getattr(other_module,string_variable_name))
22nd May 2021, 12:22 AM
visph
visph - avatar
+ 2
another option instead of eval could be using a dictionary or a class. dictionary example: dict[‘I’] = [1,2,3] class example: class myClass(): pass myString = myClass() myString.I = [1,2,3]
22nd May 2021, 1:21 AM
you are smart. you are brave.
you are smart. you are brave. - avatar
+ 1
l = [1,2,3] s = 'l' print(eval(s))
22nd May 2021, 12:27 AM
Vitaly Sokol
Vitaly Sokol - avatar
+ 1
eval == evil well, eval() works too, but should be avoided as could be used to do anything else (unsafe) if the string is given by untrusted user ^^
22nd May 2021, 12:31 AM
visph
visph - avatar
+ 1
_dict = {"l" : [1,2,3,4]} s = "l" print(_dict[s]) This si the best way i just found for doing that, It works, because you can call a dictionary Index by string. For accesing a value from the list you just: _dict[s][value_index]
22nd May 2021, 5:21 PM
6hpxq9
6hpxq9 - avatar
0
In any programming language the same pedagogy applies - iterate through the list and list the items đŸŒ»
23rd May 2021, 1:08 AM
Sanjay Kamath
Sanjay Kamath - avatar
0
No it doesn't print list of l it just print letter l
23rd May 2021, 3:42 PM
Ashwin_sanadi
0
Yeah!!!! print(s)
28th Jul 2021, 3:46 PM
CGO!
CGO! - avatar
- 1
Yah. Answer the same, as Yr. code. sum & findings. All programming languages code work in similar format {fashion} °~° ;,. đŸ˜đŸ˜’đŸ‘„đŸ‘„đŸ“œ
23rd May 2021, 12:19 PM
Asim Farheen ⭐⭐đŸ€ș👿👿
Asim  Farheen ⭐⭐đŸ€ș👿👿 - avatar