zubin patel
zubin patel

Reputation: 19

Obtain value of list and its index mentioned together in a String in Python

x=["zubin","viral","rushil"]
param=["x[0]","x[1]","x[2]"]
for paramValue in param:
    p=paramValue # here i want to read "x[0]" and want to obtain value "zubin"
    print(p) # This should print "zubin"

I want to read param and get the value of X list Your's Thankful

Upvotes: 0

Views: 67

Answers (2)

jpp
jpp

Reputation: 164673

You should find a better way to reference your list, for example via integer indexing. But here's one way using eval. Note there are security risks involved, so be sure your inputs are safe.

x = ["zubin", "viral", "rushil"]
param = ["x[0]", "x[1]", "x[2]"]

for p in param:
    print(eval(p))

zubin
viral
rushil

Upvotes: 1

Diana
Diana

Reputation: 377

If you need the index and the value you can use enumerate in pyhon

for index, paramValue in enumerate(param):
    p=paramValue
    i = index 

Upvotes: 2

Related Questions