By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,994 Members | 1,166 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,994 IT Pros & Developers. It's quick & easy.

Need help creating the union of two lists (help a noob)

P: 9
I'm trying to create a function which would look like this when running:
>> union([1, 2, 3],[3, 4, 5])
[1, 2, 3, 4, 5]
>> union([1, 2, 3],[])
[1, 2, 3]

I have written the following code:
Expand|Select|Wrap|Line Numbers
  1. def union(l1, l2):
  2.     finalList = []
  3.     i = 0
  4.     j = 0
  5.     while i <= len(l1):
  6.         while j <= len(l2):
  7.             if l1[i] is l2[j]:
  8.                 j = j + 1
  9.             elif l1[i] <> l2[j]:
  10.                 finalList = finalList + [l1[i]]
  11.                 j = j + 1
  12.         i = i + 1
  13.     return finalList
  14. print union([1, 2, 3], [3, 4 , 5])
I get the following error:
IndexError: list index out of range

for line 7

Why is this occurring? I'd like to believe that the concept in itself is correct but have a simple flaw in the commands written. Or do i make a totally logical error?

Thanks for any help!
Nov 18 '08 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Assuming the first list has only unique elements, I would approach it this way:
1. copy list 1 (resultList = list1[:])
2. iterate on list 2 with a for loop
3. if the current element in no in resultList, append it
4. return resultList
Nov 18 '08 #2

bvdet
Expert Mod 2.5K+
P: 2,851
The reason you are getting the IndexError is because your while loop only exits when i and j are equal to the length of the lists. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> list1 = [1,2,3]
  2. >>> len(list1)
  3. 3
  4. >>> list1[len(list1)]
  5. Traceback (most recent call last):
  6.   File "<interactive input>", line 1, in ?
  7. IndexError: list index out of range
  8. >>> 
Nov 18 '08 #3

P: 9
Thanks alot for the help!
Nov 18 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.