'after i print a list, it just despeared

In the following code, first create a list collection in the loadDataSet () function, and then use the map function to convert it into a set D ,after that,it can only print once and become enpty.Does anyone know what is going on here? thank you.

def loadDataSet():
    return [ [ 1, 3, 4 ], [ 2, 3, 5 ], [ 1, 2, 3, 5 ], [ 2, 5 ] ]

if __name__ == '__main__':
    myDat = loadDataSet()
    D = map( set, myDat )
    print("first print:    ",list(D))
    print("second print:    ",list(D))
    print("len of D:    ",len(list(D)))

i use python 3.5.2 and the output is :

first print:     [{1, 3, 4}, {2, 3, 5}, {1, 2, 3, 5}, {2, 5}]
second print:     []
len of D:     0


Solution 1:[1]

The reason is because of the behavior of map() function itself. It returns a generator, which can only be consumed once. This means, map can only execute the function to the list of given inputs once and return the resulting object. After that, the generator is exhausted and cannot be used to generate the same result. Therefore, the practice is to save the return value in a variable if you are going to use it more than once.

Solution 2:[2]

map creates an iterator, that can only be iterated once. The second time you call list, D is already empty since it has been iterated through already. If you want to iterate through it multiple times, do D=list(map(set, myDat))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SuperStormer
Solution 2 SuperStormer