Python range() and zip() object type

前端 未结 3 457
攒了一身酷
攒了一身酷 2020-12-01 04:24

I understand how functions like range() and zip() can be used in a for loop. However I expected range() to output a list - much like <

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 04:47

    Range (xrange in python 2.*) objects are immutable sequences, while zip (itertools.izip repectively) is a generator object. To make a list from a generator or a sequence, simply cast to list. For example:

    >>> x = range(10) 
    >>> list(x)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    But they differ in a way how elements are generated. Normal generators are mutable and exaust their content if iterated, while range is immutable, and don't:

    >>> list(x) # x is a range-object
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # second cast to list, contents is the same
    >>> y = zip('abc', 'abc')
    >>> list(y) # y is a generator
    [('a', 'a'), ('b', 'b'), ('c', 'c')]
    >>> list(y) 
    [] # second cast to list, content is empty!
    

提交回复
热议问题