1

I have two lists:

a = ['a', 'b', 'c']
b = [1]

I want my output as:

a, 1
b, 1
c, 1

Tried doing this:

for i, j in zip(a, b):
    print i, j 

I get only a, 1. How can I make it right?

This is my actual scenario:

 if request.POST.get('share'):
            choices = request.POST.getlist('choice')
            person = request.POST.getlist('select')
            person = ''.join(person)
            person1 = User.objects.filter(username=person)
            for i, j in izip_longest(choices, person1, fillvalue=person1[-1]):
                start_date = datetime.datetime.utcnow().replace(tzinfo=utc)
                a = Share(users_id=log_id, files_id=i, shared_user_id=j.id, shared_date=start_date)
                a.save()
            return HttpResponseRedirect('/uploaded_files/')
2
  • I am not sure what type of object does User.objects.filter(username=person) returns, may be it returns an iterator? Commented Jan 23, 2013 at 6:35
  • Never mind! Replacing with 0 solved the problem Commented Jan 23, 2013 at 6:37

2 Answers 2

5

You should probably use itertools.izip_longest() here:

In [155]: a = ['a', 'b', 'c']

In [156]: b = [1]

In [158]: for x,y in izip_longest(a,b,fillvalue=b[-1]):
   .....:     print x,y
   .....:     
a 1
b 1
c 1

In case of zip() as the length of b is just one, so it is going to return only one result. i.e it's result length equals min(len(a),len(b))

But in case of izip_longest the result length is max(len(a),len(b)), if fillvalue is not provided then it returns None.

Sign up to request clarification or add additional context in comments.

1 Comment

@user1881957 eh! never heard of that error before, you can use b[0].
1

OK, i'm late by at least one hour, but what about this idea:

a = ['a', 'b', 'c']
b = [1]

Since the docs on zip state

The returned list is truncated in length to the length of the shortest argument sequence.

what about turning the list a to the shorter argument? And since everything is shorter than a cycle that runs forever, let's try

import itertools

d = zip(a, itertools.cycle(b))

Thanks to Ashwini Chaudhary for bringing the itertools to my attention ;)

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.