0

I have 3 lists I created and I want to append them from the sql query output. I thought of created them as string as lst and append the output but I get the error below.

list_A1 = []
list_A2 = []
list_A3 = []


for i, name  in enumerate(dataset['name'][1]['price']):
   .
   .
   .

   id_list = pd.read_sql_query(q, con=db)[price].tolist()
   lst = f"{lst_name}_{id}"

   #lst created the 3 list above.        

   lst.append(id_list).astype(int)

Error : AttributeError: 'str' object has no attribute 'append'

Edit:

What I mean is on each loop lst = list_A1.. and each of those lists gets populated with the data from the sql query

james
  • 55
  • 5
  • `lst.append(id_list).astype(int)` will cause a problem too – Mad Physicist Aug 19 '21 at 12:54
  • you can't create variable using `f"{lst_name}_{id}"` - you may only use it as key in dictionary `all_lists[f"{lst_name}_{id}"] = []` – furas Aug 19 '21 at 12:55
  • `lst` is a string object. You cannot perform an append on it.. You can concatenate your `lst` with a `+` to `str(id_list)` – voidone Aug 19 '21 at 12:57

2 Answers2

1

You can't create variable using string f"{lst_name}_{id}". You may only use it as key in dictionary all_lists[f"{lst_name}_{id}"] = []. And you should use dictionary

all_lists = {
   "list_A1": [],
   "list_A2": [],
   "list_A3": [],
}

for ... in ...:

   id_list = ....astype(int).tolist()
 
   key = f"{lst_name}_{id}"

   lst = all_lists[key]
   
   lst.append( id_list )

You could do it even dinamically

all_lists = {}  # empty dictionary

for ... in ...:

   id_list = ....astype(int).tolist()

   key = f"{lst_name}_{id}"

   # create list if not exists yet
   if key not in all_lists:
       all_lists[key] = []

   lst = all_lists[key]
   
   lst.append( id_list )

BTW: You can create variable with vars() or similar functions but it is not preferred. You have dictionary for this.

furas
  • 134,197
  • 12
  • 106
  • 148
  • how do I call the list outside the loop? – james Aug 19 '21 at 13:13
  • `all_lists[key]` ie `all_lists["list_A1"]`. Because all lists are in dictionary so you can use them in `for`-loop and make code shorter. `for lst in all_lists.values(): ...` – furas Aug 19 '21 at 13:17
1

You can try follows,

list_A1 = []
list_A2 = []
list_A3 = []
for id_ in range(1,4,1):
    lst = f"list_A1"
    vars()[lst].append(id_)
print(list_A1)

Output

[1, 2, 3]

Reference

  1. How do I create variable variables?
Rinshan Kolayil
  • 1,111
  • 1
  • 9
  • 14