0

I am running this code on Python3 shell.

numberList = [1, 2, 3]
strList = ['one', 'two', 'three']

result=zip(numberList, strList)

resultSet=set(result)   #1
resultList=list(result)  #2

print(resultSet)
print(resultList)

and I am very surprised with the outcome :

{(1, 'one'), (3, 'three'), (2, 'two')}
[]            <<< Why?

Further, when I swap line#1 with line#2, the outcome is similar to the earlier one:

set()         <<< Why? 
[(1, 'one'), (2, 'two'), (3, 'three')]

What could be the reason behind later one being empty? Am I missing any concept here? FYI, I am relatively new to Python.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
  • 2
    `zip` gives you an iterable... `list` and `set` will consume that iterable making it effectively "empty"... following attempts to consume it will have nothing to consume. Think I've seen Q/As with various examples and how you to need to do it... I'll have a look... – Jon Clements Aug 19 '18 at 06:52
  • 1
    Additionally, I would suggest doing `resultList=list(result); resultSet = set(resultList)` – cs95 Aug 19 '18 at 06:52
  • @JonClements ok, that makes sense now. Didn't know how to google it. :) – Saurav Sahu Aug 19 '18 at 06:53

1 Answers1

0

This happens because result=zip(numberList, strList) returns an iterator. It is similar to what itertools.izip did in python 2.x Previously in python 2 zip used to return tuple.

From python 3 zip returns an iterator. An iterator returns value only once. When second time one tries to iterate over it then gives no output.

If you need to use the it again you should consider using it as

numberList = [1, 2, 3]
strList = ['one', 'two', 'three']

result=list(zip(numberList, strList)) # check the "list" keyword added 


resultList=list(result)  #2
resultSet=set(result)   #1

print(resultSet)
print(resultList)
Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
  • Your "answer" isn't nearly half as descriptive as the comments, would you consider putting some effort into the answer please? – cs95 Aug 19 '18 at 06:54
  • Edited the answer. I realised after posting that its only giving you a hint than an answer why it is behaving such a way – Arghya Saha Aug 19 '18 at 07:05