-2

I initialized characters in a list without using quotes. I want to update every value in the list so that each element in the list is converted to string so that i can use the list.

list1=[1,2,3,A,B]
for i in range(len(list1)):
    list1[i]=str(list1[i])
print(list1)

I tried to update every element in the list by converting it to a string but even then i got the error.

Error Message: Traceback (most recent call last): File "C:/Users/hp/PycharmProjects/pythonProject/any.py", line 1, in list1 = [1,2,3,A,B] NameError: name 'A' is not defined Process finished with exit code 1

3 Answers3

0

Assuming that A and B are already defined in your code, You can use list comprehension :

list1 = [1,2,3,A,B]
strlist = [str(n) for n in  list1]
Omkar76
  • 1,317
  • 1
  • 8
  • 22
0

You can't initialize characters in a list without using quotes. But you can use like..

list1 = [1,2,3,'A','B']

str_list = [str(n) for n in  list1]

print(str_list)
deadshot
  • 8,881
  • 4
  • 20
  • 39
0

Assuming all variables are unique, you can solve it with locals() method:

A = 4
B = 5
list1 = [1,2,3,A,B]

list2 = [None] * len(list1)

items = list(locals().items())

for i in range(len(list1)):
    for k,v in items:
        if v == list1[i]:
            list2[i] = k
            break
    if list2[i] is None:
        list2[i] = str(list1[i])
    
print(list2)

If not, please see this question for more information: Getting the name of a variable as a string

Konrad Talik
  • 912
  • 8
  • 22
  • Thank you bro. Though it didn't worked for all characters it answered my question correctly. I am trying it for so many days whether it is possible or not . Really nice effort @ktalik – Anudeep Kosuri Sep 14 '20 at 07:11