-2

I have a ticker and I want to check a specific list of tickers to see if the ticker is found. If it is found, it will replace it.

The new tickers come from another data source and therefore do not know which specific list of tickers to check. In order to find that list, I can pass the lists name as a string but upon iterating the code (naturally) recognizes this as string as opposed to a list to iterate.

Is there a way to have the code/function recognize that the string is actually a specific list to be checked? In reading other questions, I know this may not be possible...in that case what is an alternative?

list_1=['A','B']
list_2=['C','D']

old_ticker='A'
new_ticker='E'
assigned_list='list_1'

def replace_ticker(old_ticker,new_ticker,list):
    for ticker in list:
        if new_ticker in list:
            return
        else:
            list.append(new_ticker)
            list.remove(old_ticker)

replace_ticker(old_ticker,new_ticker,assigned_list)

3 Answers3

0

There are at least two possibilities:

1 As noted in comments kind of overkill but possible:

Use eval() to evaluate string as python expressions more in the link: https://thepythonguru.com/python-builtin-functions/eval/

For example:

list_name = 'list_1'
eval('{}.append(new_ticker)'.format(list_name))

2 Second

Using locals() a dictionary of locally scoped variables similiar to the other answers but without the need of creating the dict by hand which also requires the knowledge of all variables names.

list_name = 'list_1'
locals()[list_name].append(new_ticker)
CodeSamurai777
  • 3,285
  • 2
  • 24
  • 42
  • You might also use a sledgehammer to crack a nut. – Stop harming Monica Jul 24 '19 at 16:59
  • The question is in short how to convert a string into a recognizable variable for the sake of being complete all possibilities should be listed. I am not claiming it is a good practice but it is a possibility is it not? – CodeSamurai777 Jul 24 '19 at 17:04
0

You key the needed lists by name in a dictionary:

ticker_directory = {
    "list_1": list_1,
    "list_2": list_2
}

Now you can accept the name and get the desired list as ticker_directory[assigned_list].

Prune
  • 76,765
  • 14
  • 60
  • 81
0
list_1=['A','B']
list_2=['C','D']

lists = {
    'list_1':list_1,
    'list_2':list_2
    }

old_ticker='A'
new_ticker='E'
assigned_list='list_1'

def replace_ticker(old_ticker,new_ticker,list_name):
    if old_ticker not in lists[list_name]:
            return
    else:
        lists[list_name].append(new_ticker)
        lists[list_name].remove(old_ticker)

replace_ticker(old_ticker,new_ticker,assigned_list)

print(lists[assigned_list])

This is the complete program from what i perceived. @prune already answered this, I have just given the whole solution

Piyush Kumar
  • 191
  • 1
  • 10