Create an empty list in python with certain size

后端 未结 15 1399
有刺的猬
有刺的猬 2020-11-22 12:00

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed

相关标签:
15条回答
  • 2020-11-22 12:31

    You can .append(element) to the list, e.g.: s1.append(i). What you are currently trying to do is access an element (s1[i]) that does not exist.

    0 讨论(0)
  • 2020-11-22 12:32

    I'm surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists

    x = [[] for i in range(10)]
    
    0 讨论(0)
  • 2020-11-22 12:33

    There are two "quick" methods:

    x = length_of_your_list
    a = [None]*x
    # or
    a = [None for _ in xrange(x)]
    

    It appears that [None]*x is faster:

    >>> from timeit import timeit
    >>> timeit("[None]*100",number=10000)
    0.023542165756225586
    >>> timeit("[None for _ in xrange(100)]",number=10000)
    0.07616496086120605
    

    But if you are ok with a range (e.g. [0,1,2,3,...,x-1]), then range(x) might be fastest:

    >>> timeit("range(100)",number=10000)
    0.012513160705566406
    
    0 讨论(0)
提交回复
热议问题