How to Reduce Code Duplication of If-Else Statements in Python
<p>I'm a student with the very bad habit of duplicating code all over the place, which is something I want to change.</p>

<p>Below, I have a snippet of code from a function I'm writing. Quick explanation: The code would look at an HR website for a person, and return info about the employees he's managing (assuming he manages anyone).</p>

<p>There are two types of employees: regular employees and contract workers. On the website, regular employees underneath the manager would all be listed under employeeList, and the contractors would be listed under contractWorkerList.</p>

<pre><code>response = opener.open('myFakeOrgHierarchy.com/JohnSmith_The_Manager')
allDataFromPage = (response.read())
jsonVersionOfAllData = json.loads(allDataFromPage)

listOfAllReports = []

numOfEmployeeDirectReports = len(jsonVersionOfAllData['employeeList']['list'])
numOfContractWorkerReports = len(jsonVersionOfAllData['contractWorkerList']['list'])

if numOfEmployeeDirectReports != 0:
    for i in range(0, numOfEmployeeDirectReports, 1):
        workerInfo = {}
        workerInfo['empLname'] = jsonVersionOfAllData['employeeList']['list'][i]['lastName']
        workerInfo['empFname'] = jsonVersionOfAllData['employeeList']['list'][i]['firstName']
        listOfAllReports.append(workerInfo)

if numOfContractWorkerReports != 0:
    for i in range(0, numOfContractWorkerReports, 1):
        workerInfo = {}
        workerInfo['empLname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['lastName']
        workerInfo['empFname'] = jsonVersionOfAllData['contractWorkerList']['list'][i]['firstName']
        listOfAllReports.append(workerInfo)
</code></pre>

<p>As you can see, I have several lines of code that are almost identical to other lines, with only small variations. Is there a way to check both contractWorkerList and employeeList to see if they're not empty, and (assuming they're not empty) go through both contractWorkerList and employeeList and grab values without duplicating the code?</p>

<p>(Since I'm a relative beginner, any simple examples you could provide with your recommendations would be much appreciated)</p>