0

The objective is to create a list comprehension that outputted two values.

The for loops look like below

paper_href_scopus = []
paper_title = []
for litag in all_td.find_all('a', {'class': 'ddmDocTitle'}):
    paper_href_scopus.append(litag['href'])
    paper_title.append(litag.text)

While creating list comprehension as below work without any error

[(paper_href_scopus.append(litag['href']), paper_title.append(litag.text)) \
   for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})]

Modifying the list comprehension as below:

paper_href_scopus, paper_title = [(litag['href'], litag.text) \
    for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})]

resulting an error of :

ValueError: not enough values to unpack (expected 2, got 1)

May I know how such an error can be avoided?

mpx
  • 3,081
  • 2
  • 26
  • 56
  • `x, y = zip(*[(litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})])` – han solo Aug 01 '20 at 09:31

1 Answers1

2

You can just use zip like,

>>> paper_href_scopus, paper_title = zip(*[(litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})])

Also, no need to create the list inside, you can use a genexpr, but i don't think it will matter here. Neverthless:

>>> paper_href_scopus, paper_title = zip(*((litag['href'], litag.text) for litag in all_td.find_all('a', {'class': 'ddmDocTitle'})))

Note:

As suggested by balandongiv, here's a link to genexpr usage and another link to official docs

han solo
  • 6,390
  • 1
  • 15
  • 19
  • 1
    Hi Han, thanks for the input especially the `genexpr`. One request, can you edit your answer and place the following link to genexpr: https://stackoverflow.com/a/5165222/6446053. This may help future reader – mpx Aug 01 '20 at 09:39
  • 1
    @balandongiv Sure :) – han solo Aug 01 '20 at 09:40
  • Thanks for the update @han, btw, if have another problem with your proposed solution for some condition, appreciate if you can have a look at the thread: https://stackoverflow.com/questions/63204196/getting-error-not-enough-values-to-unpack-when-using-list-comprehension-toget – mpx Aug 01 '20 at 10:32