473,379 Members | 1,191 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

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

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
3 1823
2,851 Expert Mod 2GB
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
2,851 Expert Mod 2GB
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
Thanks alot for the help!
Nov 18 '08 #4

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

Similar topics

by: Mickel Grönroos | last post by:
Hi! Are there any standard list methods for getting the intersection and difference of two lists? (The union is easy ("list1.extend(list2)"), unless you want it to contain unique values.) ...
by: Wiebke Pätzold | last post by:
import sys Hi all, At the beginning there is a table (database) with different columns. So I create a search operator to look for regular expressions. First I start the search only in one...
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
by: Neculai Macarie | last post by:
Hi! Using Union and Order By gives strange behaviour in the following test-case: drop table if exists gallery; drop table if exists gallery_categ; # create test tables create table gallery...
by: Alicia | last post by:
Hello everyone based on the data, I created a union query which produces this. SELECT ,,, 0 As ClosedCount FROM UNION SELECT ,, 0 AS OpenedCount, FROM ORDER BY , ;
by: Neil Zanella | last post by:
Hello, I would like to know what the C standards (and in particular the C99 standard) have to say about union initializers with regards to the following code snippet (which compiles fine under...
by: Randall Skelton | last post by:
I have a number of tables with the general structure: Column | Type | Modifiers -----------+--------------------------+----------- timestamp | timestamp with time zone |...
by: tothlaci | last post by:
Hi, I have an asp site where I sell some products. Product categories are stored in different tables. There are different asp product pages, which collects data from these tables. I have also...
by: cephal0n | last post by:
Hi All! First of I apologize for my previews post needing help on union select and not providing so more explanation, but thank you very much for your opinion and sugestion. I have thought about my...
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.