Home > Mobile >  adding multiple data in return to list at once
adding multiple data in return to list at once

Time:06-04

I want to add the return data from a def to multiple lists in a single line, is there a way to do this?

My Code:

def getData():
    try:
        aprovince, atown, aneighbourhood = (
            soup.find("ul", {"class": "short-info-list"}).findNext("li").text.strip(),
            soup.find("ul", {"class": "short-info-list"}).findNext("li").findNext("li").text.strip(),
            soup.find("ul", {"class": "short-info-list"}).findNext("li").findNext("li").findNext("li").text.strip()
        return(aprovince, atown, aneighbourhood)
    except:
        return False

for link in links:
    page = requests.get(link)
    soup = BeautifulSoup(page.content, "html.parser")
    if (check()):
        province.append(), town.append(), neigbourhood.append() = getData()

I don't want to assign the data returned from getData to a variable first and then add it to lists one by one from that variable, can't I handle this directly where I call getData?

(getData actually takes 12 different data, I cropped it a bit when posting the code here)

Assigning 12 data to a temporary data and then adding them one by one to lists seems like code pollution

CodePudding user response:

No, you need to save the result in a variable.

p, t, n = getData()
province.append(p)
town.append(t)
neighborhood.append(n)

If you had lots of lists you could do them all in a loop:

lists = [province, town, neighborhood]
for l, d in zip(lists, getData()):
    l.append(d)
  • Related