0

I have a list of (x,y) tuples ("lt" in the example, below). I want to extract the x's and y's so I can perform a Pearson correlation calculation. If I execute this code:

lt = [(1,2), (3,4), (5,6)]
print(lt)
unzip_list = zip(*lt)
xs = list(unzip_list)[0]
print(xs)

As expected, I get this result:

[(1, 2), (3, 4), (5, 6)]
(1, 3, 5)

If I execute this code:

lt = [(1,2), (3,4), (5,6)]
print(lt)
unzip_list = zip(*lt)
ys = list(unzip_list)[1]
print(ys)

As expected, I get this result:

[(1, 2), (3, 4), (5, 6)]
(2, 4, 6)

But if I execute this code:

lt = [(1,2), (3,4), (5,6)]
print(lt)
unzip_list = zip(*lt)
xs = list(unzip_list)[0]
print(xs)
ys = list(unzip_list)[1]
print(ys)

I get this error on line 6!

[(1, 2), (3, 4), (5, 6)]
(1, 3, 5)

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-302-81d917cf4b2d> in <module>()
      4 xs = list(unzip_list)[0]
      5 print(xs)
----> 6 ys = list(unzip_list)[1]
      7 print(ys)

IndexError: list index out of range
cs95
  • 379,657
  • 97
  • 704
  • 746
JGV
  • 163
  • 3
  • 14

1 Answers1

1

zip returns an iterator, so once you call list on it it gets empty

Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> zip([1], [1])
<zip object at 0x7fcd991991c8>
>>> a = zip([1], [1])
>>> list(a)
[(1, 1)]
>>> list(a)
[]

You can use tee to get more than one iterator:

>>> from itertools import tee
>>> a, b = tee(zip([1], [1]), 2)
>>> list(a)
[(1, 1)]
>>> list(b)
[(1, 1)]
>>> list(a)
[]
>>> list(b)
[]
Paweł Kordowski
  • 2,688
  • 1
  • 14
  • 21