Concatenating two range function results

前端 未结 8 1250
臣服心动
臣服心动 2020-11-27 17:04

Does range function allows concatenation ? Like i want to make a range(30) & concatenate it with range(2000, 5002). So my concatenated range w

相关标签:
8条回答
  • 2020-11-27 17:32

    You can use itertools.chain for this:

    from itertools import chain
    concatenated = chain(range(30), range(2000, 5002))
    for i in concatenated:
         ...
    

    It works for arbitrary iterables. Note that there's a difference in behavior of range() between Python 2 and 3 that you should know about: in Python 2 range returns a list, and in Python3 an iterator, which is memory-efficient, but not always desirable.

    Lists can be concatenated with +, iterators cannot.

    0 讨论(0)
  • 2020-11-27 17:37

    With the help of the extend method, we can concatenate two lists.

    >>> a = list(range(1,10))
    >>> a.extend(range(100,105))
    >>> a  
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 101, 102, 103, 104]
    
    0 讨论(0)
提交回复
热议问题