Python list initialization using multiple range statements

后端 未结 7 1539
误落风尘
误落风尘 2021-01-07 22:15

I want one long list, say [1,2,3,4,5,15,16,17,18,19] as an example. To initialize this, I try typing:

new_list = [range(1,6),range(15,20)]

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 23:05

    range returns a list to begin with, so you need to either concatenate them together with + or use append() or extend().

    new_list = range(1,6) + range(15,20)
    

    or

    new_list = range(101,6284)
    mew_list.extend([8001,8003,8010])
    mew_list.extend(range(10000,12322))
    

    Alternatively, you could use itertools.chain() as shown in Shawn Chin's answer.

提交回复
热议问题