0

I'm trying to loop through two lists and create tuple with it and then return list.

m = re.findall(reg, request) //List of all names from website
i = re.findall(reg2, request) //job title.

lst = []
for name in m:
    for job in i: #<======= Can't access name after this point
        if name and job:
            tub = (name, job)
            if tub not in lst:
                lst.append(tub)
        elif name:
            tub = (name, None)
            if tub not in lst:
                lst.append(tub)

print(lst)
return lst

With this input it is:

print(m) -> ['Name Nameson']
print(i) -> [] 

But it seem like i can't access the name variable in the inner loop. If set print(name) in the outer loop it shows but not in the inner. So the return is always [].

I'm new to python what I'am i doing wrong here?

4
  • Can you show print i and print m outputs. And the rest of your code if possible.. there should be more because you have a return without a function... Commented Jul 29, 2013 at 22:53
  • I updated the code with print statement. Commented Jul 29, 2013 at 22:56
  • 4
    your i is empty!! It is not going to enter the second loop.. Commented Jul 29, 2013 at 22:58
  • of course, It's time to take break apparently. Commented Jul 29, 2013 at 22:59

4 Answers 4

1
for i in range(10):
    for j in range(10):
        print i,j

you are doing something wrong ... its hard to say more without seeing your input ... in your code your i = []

so

for item in []:
   print "this will never print"
Sign up to request clarification or add additional context in comments.

Comments

1

Your output says it all, list i is an empty list, so your nested job loop won't event loop once. So it isn't that 'name' isn't being carried into the nested loop, it's that you aren't even going into the nested loop block in the first place.

Comments

1

I like to use functions in itertools when working with permutations of iterables. itertools.product should do what you want.

>>> from itertools import product

>>> l1 = [1, 2, 3, 4]
>>> l2 = ['a', 'b', False, 'd']

>>> list((x, y) if y else (x, None) for x, y in product(l1, l2) if x)

[(1, 'a'), (1, 'b'), (1, None), (1, 'd'), (2, 'a'), (2, 'b'), (2, None),
 (2, 'd'), (3, 'a'), (3, 'b'), (3, None), (3, 'd'), (4, 'a'), (4, 'b'),
 (4, None), (4, 'd')]

2 Comments

Thanks for pointing that out, fixed the code to better reflect the question.
and a solid answer at that (+1 for itertools)
0

Why not use list comprhension and sets instead?

list(set([(name, job) for name in m for job in i]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.