Python range() and zip() object type

前端 未结 3 466
攒了一身酷
攒了一身酷 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条回答
  •  猫巷女王i
    2020-12-01 05:04

    In Python 3.x., range returns a range object instead of a list like it did in Python 2.x. Similarly, zip now returns a zip object instead of a list.

    To get these objects as lists, put them in list:

    >>> range(10)
    range(0, 10)
    >>> list(range(10))
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> zip('abc', 'abc')
    
    >>> list(zip('abc', 'abc'))
    [('a', 'a'), ('b', 'b'), ('c', 'c')]
    >>>
    

    While it may seem unhelpful at first, this change in the behavior of range and zip actually increases efficiency. This is because the zip and range objects produce items as they are needed, instead of creating a list to hold them all at once. Doing so saves on memory consumption and improves operation speed.

提交回复
热议问题