## Workshop 4: Nested Lists¶

We're already familiar with nested lists: they are simply lists of lists. Here's an example:

In [2]:
rhymes = [['cat', 'hat', 'fat'], ['mouse', 'house', 'louse'], ['be', 'see', 'key', 'he']]


This is a list with three elements: ['cat', 'hat', 'fat'], ['mouse', 'house', 'louse'], and ['be', 'see', 'key', 'he']. We can get the second element as follows:

In [3]:
rhymes[1]

Out[3]:
['mouse', 'house', 'louse']

Here is how we can get the third element of the second list:

In [4]:
rhymes[1][2]

Out[4]:
'louse'

This is the same as going

In [5]:
['mouse', 'house', 'louse'][2]

Out[5]:
'louse'

### Maximum number of visits¶

Let's say that we have a list of lists that contains the dates of the visits each patient has made. visits[i] is the data for patient i: the dates on which patient i visited the docotor

In [6]:
visits = [[2, 6], [3, 10], [15], [23], [14]]


So for example patient 1 visited the doctor on the 3rd and the 10th, for a total of two visits.

Now, let's write a program to get the maximum number of visits, for any patient (the answer in this case is 2, since no patient has visited the doctor more than twice)

In [7]:
max_visits = 0
for patient_data in visits:
num_visits = len(patient_data)
if num_visits > max_visits:
max_visits = num_visits

print(max_visits)

2


How about the patient who visited the most times? Now, we need to also store the index of the maximum

In [8]:
max_visits = len(visits[0])
max_ind = 0    #the index of the sickest patient

for i in range(len(visits)):
num_visits = len(visits[i])
if num_visits > max_visits:
max_ind = i
max_visits = num_visits
print("Patient", max_ind , "is the sickest")

Patient 0 is the sickest


Here's another option, if you remember about list.index

In [10]:
print(num_visits.index(max(num_visits)))

0


Now, write code that displays the indices of all the patients who had the largest number of visits.

Solution:

In [9]:
num_visits = [] #contains the number of visits
#for every patient
for patient_data in visits:
num_visits.append(len(patient_data))

max_visits = max(num_visits)

for i in range(len(num_visits)):
if  num_visits[i] == max_visits:
print(i, "is one of the sickest patients")

0 is one of the sickest patients
1 is one of the sickest patients