8

I am writing some cryptographic algorithm using Python, but I have never worked with Python before.

First of all, look at this code then I'd explain the issue,

x = bytearray(salt[16:])
y = bytearray(sha_512[32:48])
c = [  i ^ j for i, j in zip( x, y )  ]

The value of x and y are ,

bytearray(b'AB\xc8s\x0eYzr2n\xe7\x06\x93\x07\xe2;')
bytearray(b'+q\xd4oR\x94q\xf7\x81vN\xfcz/\xa5\x8b')

I couldn't understand the third line of the code. In order to understand the third line, I had to look into the function zip(), I came across this question,

zip function help with tuples

According to answer in this question, the code,

zip((1,2,3),(10,20,30),(100,200,300))

will output,

[(1, 10, 100), (2, 20, 200), (3, 30, 300)]

but when I am trying to print it,

print(zip((1,2,3),(10,20,30),(100,200,300)))

I am getting this output,

<zip object at 0x0000000001C86108>

Why my output is different from the original output ?

martineau
  • 119,623
  • 25
  • 170
  • 301
Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110

1 Answers1

16

In Python 3 zip returns an iterator, use list to see its content:

>>> list(zip((1,2,3),(10,20,30),(100,200,300)))
[(1, 10, 100), (2, 20, 200), (3, 30, 300)]

c = [ i ^ j for i, j in zip( x, y ) ] is a list comprehension, in this you're iterating over the items returned from zip and doing some operation on them to create a new list.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    @Xufyan That's a list comprehension. – Ashwini Chaudhary Oct 09 '13 at 16:55
  • 1
    @Xufyan Read: [Iterator](http://docs.python.org/2/glossary.html#term-iterator). ` ` is nothing but a `repr` representation of the zip iterator object. – Ashwini Chaudhary Oct 09 '13 at 17:08
  • I notice in new version of Python most of in-build functions returns iterator instead of sequence. correct? – Grijesh Chauhan Oct 10 '13 at 04:08
  • @GrijeshChauhan Yes, `map` also returns an iterator now and `xrange()` is renamed to `range()`, and the py2.x's `range()` is not available anymore. – Ashwini Chaudhary Oct 10 '13 at 05:46
  • @hcwhsa Thanks! Can you suggest me a source where from I should explore about libraries like iteratools, Collections etc. (or Python docs are best resource).. I saw learn python good book. – Grijesh Chauhan Oct 10 '13 at 05:48
  • 1
    @GrijeshChauhan Docs are the best resource to learn about libraries, I guess no book covers these libraries properly. BTW to learn some new tricks I'd suggest: [Python Cookbook, 3rd Edition](http://shop.oreilly.com/product/0636920027072.do), a python2 version of this book is also available. – Ashwini Chaudhary Oct 10 '13 at 06:09