[Tutor] Print List

akleider at sonic.net akleider at sonic.net
Thu Sep 13 01:36:57 CEST 2012


> On 12/09/12 16:36, Ashley Fowler wrote:
>
>> def printList(lists):
>>      print("First Name\tLast Name\tCredits\tGPA")
>>      for i in lists:
>>          print (i)
>>
>>
>> Any Suggestions or Corrections?
>
> The input parameter is called 'lists' which implies that the input is
> more than one list. Try to make your input parameter names as accurate
> as possible. In this case you might think 'list' would be good, but its
> no, because list is a Python builtin word. So we would be better to
> choose something like aList or theList.
>
> Your function could have been generic in that it printed any kind of
> list but by printing a header line you have made it specific to a list
> of students. So you could call the input studentList.
>
> In general, in Python, generic functions are favoured. One way to have a
> header and be generic would be to pass the header in as a parameter too:
>
> def printList(theList, theHeader=""):
>     print(theHeader)
>     for item in theList:
>        print item
>
>
> And then you would call it with:
>
> printList(myStudentList, "First Name\tLast Name\tCredits\tGPA")
>
> Or
>
> printList(myPetList, "Name, Breed, Age")
>
> Or
>
> printList(myBlankList)   # uses the default empty header
>
> or whatever...
>
> --
> Alan G

To make it even more generic I would suggest replacing
"""   print(theHeader) """
with
"""   if theHeader:
          print(theHeader)
"""
to avoid a blank line if you don't need/want a header line.
ak
> def printList(theList, theHeader=""):
>     print(theHeader)
>     for item in theList:
>        print item
>




More information about the Tutor mailing list