[Tutor] manipulating lists
Dave Angel
davea at ieee.org
Wed Jul 29 21:29:17 CEST 2009
(You omitted a title, so I made one up. Hope it's okay)
Chris Castillo wrote:
> # Module demonstrates use of lists and set theory principles
>
> def Unite(set1, set2): # evaluate 2 lists, join both into 1 new list
> newList = []
> for item in set1:
> newList.append(item)
> for item in set2:
> newList.append(item)
> newList.sort()
> return newList
>
> def Intersect(set1, set2): # evaluate 2 lists, check for
> commonalities, output commonalities to 1 new list
> newList = []
> for item in set1:
> if item in set1 and item in set2:
> newList.append(item)
> newList.sort()
> return newList
>
> def Negate(set1, set2): # evaluate 2 lists, return negation of 1st list
> newList = []
> for item in set1:
> if item in set2:
> set1.remove(item)
> newList = set1
> return newList
>
>
> could this be done in a more elegant fashion?
>
>
Note: don't ever use tabs in source code. Use spaces to indent -
preferably 4 each. If you accidentally mix spaces and tabs, you could
have very mysterious bugs
Just by inspection - untested code:
#Use docstring. Use extend rather than append in loop. Use slice
notation to make a copy of the items in the list
def Unite(set1, set2):
""" evaluate 2 lists, join both into 1 new list"""
newList = set1[:]
newList.extend(set2)
return sorted(newList)
def Intersect(set1, set2):
""" evaluate 2 lists, check for
commonalities, output commonalities to 1 new list"""
newList = []
for item in set1:
if item in set2:
newList.append(item)
return sorted(newList)
#This one was buggy; it modified set1 in place, and returned another reference to it
def Negate(set1, set2):
""" evaluate 2 lists, items that are in first list, but not in second """
newList = set1[:]
for item in set2:
newList.remove(item)
return newList #Question: did you mean to sort this one too?
Now, could these be improved further? Absolutely. Using list comprehensions or similar techniques, some of these loops could be one-liners.
But I'm guessing you're a beginner in Python, and it's more important that you get used to writing readable, robust code than clever code.
One thing I do recommend, even at this stage, is to study set().
DaveA
More information about the Tutor
mailing list