-1

While trying to create a web crawler, I'm trying to define this function:

#a and b are lists.
def union(a, b):
    i = 0
    while i <= len(b):
        if b[i] in a :
            a = a.append(b[i])   
        i = i + 1    
    return a

then testing it, I input:

a = [1,2,3]
b = [2,4,6,9]
union(a,b)

It keeps giving me the error

TypeError: argument of type 'NoneType' is not iterable

I've seen a solution for this problem in another thread by editing my condition to if a and b[i] not in a:, but while testing, that only solves it until I append 1 element of b to a, then stops working.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
  • Please properly format your code next time. It's one click on "edit" , and one click on format as code. – Marcus Müller May 30 '16 at 17:24
  • 1
    Use [`sets`](https://docs.python.org/2/library/stdtypes.html#set), not lists. Sets have an inbuilt `union` you can take advantage of. No need to roll your own. – Akshat Mahajan May 30 '16 at 17:24
  • this is **not** how python `while` loop works. Please read a basic Python tutorial. – Marcus Müller May 30 '16 at 17:24
  • 1
    see http://stackoverflow.com/questions/16641119/why-does-append-return-none-in-this-code – Tadhg McDonald-Jensen May 30 '16 at 17:25
  • that's completely different code now, and it doesn't make sense at all. – Marcus Müller May 30 '16 at 17:26
  • I'm voting to close this question as off-topic because OP is changing code fundamentally, trying to skip past the necessity to read a basic python tutorial: at this level, it's impossible to answer. – Marcus Müller May 30 '16 at 17:26
  • 3
    `append` returns `None` so `a = a.append(b[i])` effectively overwrites the value of `a` with `None`. Just do `a.append(b[i])` – jDo May 30 '16 at 17:27
  • @MarcusMüller give them a break! This is a new user who is having trouble coding and the original code makes perfect sense, it just isn't a case one would use `while` loops in python. – Tadhg McDonald-Jensen May 30 '16 at 17:28
  • @TadhgMcDonald-Jensen I'm all yours on being nice to new users, but the point here is that we should teach new users how to help *themselves*, and in this case, not "hotfixing" something just quick, but trying to understand what one's doing wrong. – Marcus Müller May 30 '16 at 17:30

1 Answers1

0

See the updated and commented code below

#a and b are lists.
def union(a, b):
    i = 0
    while i <= len(b):
        if b[i] in a :
            # the problem lies here. append returns None
            # a = a.append(b[i])
            # this should work
            a.append(b[i])   
        i = i + 1    
    return a
saq7
  • 1,528
  • 1
  • 12
  • 25