Best and/or fastest way to create lists in python

前端 未结 4 1957
既然无缘
既然无缘 2020-11-29 00:31

In python, as far as I know, there are at least 3 to 4 ways to create and initialize lists of a given size:

Simple loop with append:

4条回答
  •  一个人的身影
    2020-11-29 01:15

    If you want to create a list incrementing, i.e. adding 1 every time, use the range function. In range the start argument is included and the end argument is excluded as shown below:

    list(range(10,20))
    [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    

    If you want to create a list by adding 2 to previous elements use this:

    list(range(10,20,2))
    [10, 12, 14, 16, 18]
    

    Here the third argument is the step size to be taken. Now you can give any start element, end element and step size and create many lists fast and easy.

    Thank you..!

    Happy Learning.. :)

提交回复
热议问题