Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, finding item in a list with variables

I am not a programmer, so this might be very basic. I am trying to find the index of a variable inside a list with the contents of a variable

name = "Carl"
num = 10
more = "stuff"

my_list = [name, num, more]

target = "num"
targetVal = "25"

print(my_list)
print(my_list.index(target))

I get

['Carl', 10, 'stuff']
ValueError: 'num' is not in list

Indexing num as variable works, but "num" will not work.

So I can't find a way of changing the num ="10" inside my list to "25". This way of a list would be perfect for what I am trying to hack together, but I can't figure out how to do it.

EDIT:

Using dictionarys instead of lists seams to be better

my_dict = {"name": "Carl", "num": "10", "more": "stuff"}
target = "num"
targetVal = "25"

print(my_dict)
print(my_dict[target])

my_dict[target] = targetVal

print(my_dict[target])

Output:

{'name': 'Carl', 'num': '10', 'more': 'stuff'}
10
25
like image 963
Beardlongo Avatar asked Jan 26 '26 19:01

Beardlongo


1 Answers

Your values in a list (my_list) are string so string should be in single or double quotes like this:

name = "Carl"
num = 10
more = "stuff"

my_list = ["name", "num", "more"]

target = "num"
targetVal = "25"

print(my_list)
print(my_list.index(target))
like image 199
Shaheer Avatar answered Jan 29 '26 08:01

Shaheer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!