marv
marv

Reputation: 37

Python3: zip in range

I'm new to Python and I'm trying to zip 2 lists together into 1, which I was already able to do. I've got 2 lists with several things in them, but I'm asking the user to input a number, which should determine the range. So i've got List1: A1, A2, A3, A4, A5, A6 and List2: B1,B2,B3,B4,B5,B6 I know how to display the 2 complete lists, but what I'm trying to do is, if the user enters number "3", the zip should only display: (A1,B1), (A2,B2), (A3,B3) instead of the whole list. So here's what I tried:

a = ["A1", "A2", "A3", "A4", "A5", "A6"]
b = ["B1", "B2", "B3", "B4", "B5", "B6"]
c = zip(a,b)
number = int(input("please enter number"))
for x in c:
    print(x[:number])

But this doesn't work. I tried to look it up, but couldn't find anything. I would be glad, if someone could help me out.

Upvotes: 2

Views: 397

Answers (3)

Valentin Lorentz
Valentin Lorentz

Reputation: 9753

When in doubt, use print:

>>> a = ["A1", "A2", "A3", "A4", "A5", "A6"]
>>> b = ["B1", "B2", "B3", "B4", "B5", "B6"]
>>> c = zip(a,b)
>>> number = 3
>>> for x in c:
...  print(x)
... 
('A1', 'B1')
('A2', 'B2')
('A3', 'B3')
('A4', 'B4')
('A5', 'B5')
('A6', 'B6')

As you can see, x is a pair, so x[:number] would only show the number first items of the pair.

What you actually want to do is show the number first pairs:

>>> c = list(zip(a,b))
>>> print(c[:3])
[('A1', 'B1'), ('A2', 'B2'), ('A3', 'B3')]

(Note that I used list() on the value returned by zip(), because zip objects as not subscriptable)

If you want to iterate instead of just printing them like this, it's easy:

>>> for x in c[:3]:
...     print(x)
... 
('A1', 'B1')
('A2', 'B2')
('A3', 'B3')

Upvotes: 3

alecxe
alecxe

Reputation: 474001

You can slice the result of zip() with itertools.islice():

>>> from itertools import islice
>>> list(islice(c, number))
[('A1', 'B1'), ('A2', 'B2'), ('A3', 'B3')]

Upvotes: 8

Aaron Christiansen
Aaron Christiansen

Reputation: 11837

You don't need a for loop here - you only need to do the operation you're trying to do once. Also, a generator object returned by zip can't be "subscripted" (accessed using []), so you need to convert it to a list first using list.

Here's some modified code that works:

a = ["A1", "A2", "A3", "A4", "A5", "A6"]
b = ["B1", "B2", "B3", "B4", "B5", "B6"]
c = list(zip(a,b))
number = int(input("please enter number"))
print(c[:number])

Example of usage and output:

please enter number 3
[('A1', 'B1'), ('A2', 'B2'), ('A3', 'B3')]

Upvotes: 3

Related Questions