1

I'm new to writing classes in Python and had a quick question. Here is some code below.

class Parse_profile():

  def __init__(self, page):
    self.page = page

  def get_title(self):
    list_of_titles = []
    for title in self.page.find_all(.....):
      list_of_titles.append(title.get_text())
    return list_of_titles

  def get_companies(self):
    list_of_companies = []
    for company in self.page.find_all(.....):
      list_of_companies.append(company)
    return list_of_companies

I want to create a third function that will take in both list_of_companies and list_of_titles (and more later on) and combine them into one list.

How do I do that?

3
  • 1
    zip(list_of_titles,list_of_companies) ? Commented Dec 17, 2015 at 0:07
  • Does this new function need information from the Parse_profile instance? Commented Dec 17, 2015 at 0:08
  • Can you explain exactly how you want to combine them into a single list? Just add all the companies to the end of the list of titles? Commented Dec 17, 2015 at 0:08

1 Answer 1

3
def get_companies_and_titles(self):
    return self.get_companies() + self.get_title()

This will get you a list with all companies followed by all titles. In case you want (company, title) tuples in your result-list, use:

def get_companies_and_titles(self):
    return zip(self.get_companies(), self.get_title())

The second option can yield unexpected results if the lists are not of the same length. Have a look at the documentation for zip and izip_longest in that case.

Sign up to request clarification or add additional context in comments.

4 Comments

I upvoted because this answers OP's question as stated... that said I am guessing this is not actually what OP meant :P
@JoranBeasley reading the question again it seems a litte ambiguous. Let's see if the author will clarify.
AHHH! Yes, this is what I was looking for. I was writing get_companies() inside the function and it was throwing an error. self.get_companies() works :-) Thank you!! I wasn't sure how to pass a function into another function inside a class.
@MorganAllen no problem, happy coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.