Main Content

zip in Python

Archive - Originally posted on "The Horse's Mouth" - 2012-07-05 08:03:36 - Graham Ellis

Zipping has become synonymouse with compressing data in programming terms; originally the use of the word in that sense came from zipping up a bag so that a whole lot of contents were held together, but these days the compression (pushing everything into the bag) is kind of expected.

Python's zip function takes us back to the older meaning - it allows two or more lists of the same length to be combined into a list of tuples, also with the same number of members.

For example, I may have two lists:
  first = [4,27,46,51]
  place = ["Melksham","Chippenham","Swindon","Didcot"]

and if I zip them together
  togeths = zip(first,place)
  print togeths

I'll get:
  [(4, 'Melksham'), (27, 'Chippenham'), (46, 'Swindon'), (51, 'Didcot')]

Image from Morguefile - attribution not required, but freely offered with thanks for the resource.