• python中创建空列表If you want to learn how to create an empty list in Python ... 如果您想学习如何在Python中高效地创建一个空列表,那么本文适合您。 You will learn: 您将学习: How to create an empty li...


    If you want to learn how to create an empty list in Python efficiently, then this article is for you.


    You will learn:


    • How to create an empty list using square brackets [].


    • How to create an empty list using list().


    • Their use cases.

    • How efficient they are (one is faster than the other!). We will use the timeit module to compare them.

      它们的效率(一个比另一个快!)。 我们将使用timeit模块进行比较。

    Let's begin! 🔅

    让我们开始! 🔅

    🔹使用方括号 (🔹 Using Square Brackets)

    You can create an empty list with an empty pair of square brackets, like this:  


    💡 Tip: We assign the empty list to a variable to use it later in our program.


    For example:


    num = []

    The empty list will have length 0, as you can see right here:

    空列表的长度为0 ,您可以在此处看到:

    >>> num = []
    >>> len(num)

    Empty lists are falsy values, which means that they evaluate to False in a boolean context:


    >>> num = []
    >>> bool(num)

    将元素添加到空列表 (Add Elements to an Empty List)

    You can add elements to an empty list using the methods append() and insert():


    • append() adds the element to the end of the list.


    • insert() adds the element at the particular index of the list that you choose.


    Since lists can be either truthy or falsy values depending on whether they are empty or not when they are evaluated, you can use them in conditionals like this:


    if num:
    	print("This list is not empty")
    	print("This list is empty")

    The output of this code is:


    This list is empty

    Because the list was empty, so it evaluates to False.


    In general:


    • If the list is not empty, it evaluates to True, so the if clause is executed.

      如果列表不为空,则计算结果为True ,因此将执行if子句。

    • If the list is empty, it evaluates to False, so the else clause is executed.

      如果列表为空,则结果为False ,因此执行else子句。

    例: (Example:)

    In the example below, we create an empty list and assign it to the variable num. Then, using a for loop, we add a sequence of elements (integers) to the list that was initially empty:

    在下面的示例中,我们创建一个空列表并将其分配给变量num 。 然后,使用for循环,将一系列元素(整数)添加到最初为空的列表中:

    >>> num = []
    >>> for i in range(3, 15, 2):

    We check the value of the variable to see if the items were appended successfully and confirm that the list is not empty anymore:  


    >>> num
    [3, 5, 7, 9, 11, 13]

    💡 Tip: We commonly use append() to add the first element to an empty list, but you can also add this element calling the insert() method with index 0:


    >>> num = []
    >>> num.insert(0, 1.5) # add the float 1.5 at index 0
    >>> num

    🔸使用list()构造函数 (🔸 Using the list() Constructor)

    Alternatively, you can create an empty list with the type constructor list(), which creates a new list object.


    According to the Python Documentation:


    If no argument is given, the constructor creates a new empty list, [].


    💡 Tip: This creates a new list object in memory and since we didn't pass any arguments to list(), an empty list will be created.

    提示:这将在内存中创建一个新的列表对象,由于我们没有将任何参数传递给list() ,因此将创建一个空列表。

    For example:


    num = list()

    This empty list will have length 0, as you can see right here:

    空列表的长度为0 ,您可以在此处看到:

    >>> num = list()
    >>> len(num)

    And it is a falsy value when it is empty (it evaluates to False in a boolean context):

    当它为空时,它是一个伪造的值(在布尔上下文中其值为False ):

    >>> num = list()
    >>> bool(num)

    例: (Example:)

    This is a fully functional list, so we can add elements to it:


    >>> num = list()
    >>> for i in range(3, 15, 2):

    And the result will be a non-empty list, as you can see right here:


    >>> num
    [3, 5, 7, 9, 11, 13]

    🔹用例 (🔹 Use Cases)

    • We typically use list() to create lists from existing iterables such as strings, dictionaries, or tuples.


    • You will commonly see square brackets [] being used to create empty lists in Python because this syntax is more concise and faster.


    🔸效率 (🔸 Efficiency)

    Wait! I just told you that [] is faster than list()...

    等待! 我只是告诉你[]list()更快...

    But how much faster?


    Let's check their time efficiencies using the timeit module.


    To use this module in your Python program, you need to import it:


    >>> import timeit

    Specifically, we will use the timeit function from this module, which you can call with this syntax:

    具体来说,我们将使用此模块中的timeit函数 ,您可以使用以下语法进行调用:

    💡 Tip: The code is repeated several times to reduce time differences that may arise from external factors such as other processes that might be running at that particular moment. This makes the results more reliable for comparison purposes.

    💡 提示:该代码重复了几次,以减少由外部因素(例如,可能在该特定时刻运行的其他进程)引起的时间差异。 这使得结果更加可靠,可用于比较。

    🚩 On your marks... get set... ready! Here is the code and output:

    marks 在您的标记上...准备好...准备好了! 这是代码和输出:

    First, we import the module.


    >>> import timeit

    Then, we start testing each syntax.


    测试[](Testing []:)

    >>> timeit.timeit('[]', number=10**4)

    测试list()(Testing list():)

    >>> timeit.timeit('list()', number=10**4)

    💡 Tip: Notice that the code that you want to time has to be surrounded by single quotes '' or double quotes "". The time returned by the timeit function is expressed in seconds.

    提示:请注意,要计时的代码必须用单引号''或双引号""包围。 timeit函数返回的时间以秒为单位。

    Compare these results:


    • []: 0.0008467000000109692


    • list(): 0.002867799999989984


    You can see that [] is much faster than list(). There was a difference of approximately 0.002 seconds in this test:

    您可以看到[]list()快得多。 此测试相差约0.002秒:

    >>> 0.002867799999989984 - 0.0008467000000109692

    I'm sure that you must be asking this right now: Why is list() less efficient than [] if they do exactly the same thing?


    Well... list() is slower because it requires looking up the name of the function, calling it, and then creating the list object in memory. In contrast, [] is like a "shortcut" that doesn't require so many intermediate steps to create the list in memory.

    好吧... list()较慢,因为它需要查找函数名称,调用它,然后在内存中创建列表对象。 相反, []就像一个“快捷方式”,不需要太多的中间步骤即可在内存中创建列表。

    This time difference will not affect the performance of your program very much but it's nice to know which one is more efficient and how they work behind the scenes.


    Summary总结 (🔹 In Summary)

    You can create an empty list using an empty pair of square brackets [] or the type constructor list(), a built-in function that creates an empty list when no arguments are passed.


    Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.


    I really hope that you liked my article and found it helpful. Now you can create empty lists in your Python projects. Check out my online courses. Follow me on Twitter. 👍

    我真的希望您喜欢我的文章并发现它对您有所帮助。 现在,您可以在Python项目中创建空列表。 查看我的在线课程 。 在Twitter上关注我。 👍

    If you want to dive deeper into lists, you may like to read:


    翻译自: https://www.freecodecamp.org/news/python-empty-list-tutorial-how-to-create-an-empty-list-in-python/


  • python3 判断空列表 @(python3) 有判断列表是否为空的需求,试了好多方式,比如: a = [] if a is not None: COMMAND a = [] if a[0] is None: ...各种乱七八糟的逻辑,...以上这篇python3 判断列表是一个空列表
  • python如何创建空列表

    万次阅读 2020-01-09 07:32:12
    Python中创建新的空列表的方法有两种,如下: 或 list()比[]慢,因为: 1、有符号查找; 2、有函数调用;...















  • Python 创建多维空列表

    千次阅读 2020-07-23 01:04:45
    # 以三维空列表为例 3d_list = [ [ [] for j in range(9) ] for i in range(9) ] 列表推导式的生成值可以是空列表 [],因此只要利用列表推导式的复合循环即可轻松达到目的
    # 以三维空列表为例
    3d_list = [ [ [] for j in range(9) ] for i in range(9) ]

    列表推导式的生成值可以是空列表 [],因此只要利用列表推导式的复合循环即可轻松达到目的

  • I want a line of code which will create an empty list whose name is determined by an incrementing variable.Everywhere I"ve looked thus far has been unhelpful. They suggest instead something which...

    I want a line of code which will create an empty list whose name is determined by an incrementing variable.

    Everywhere I"ve looked thus far has been unhelpful. They suggest instead something which makes a list of empty lists or using a dictionary. This is not what I want, I want a line (or several) of code which just creates an empty list (which is not part of a dictionary or a list of lists, a stand alone entity). I want these lists to be distinct, distinguished by a variable which increments by 1 every time a new empty list is created.

    These empty lists can"t be made in one batch at the very beginning as I intend to make and delete these lists throughout a recursive function. I need to make multiple lists as my intention is for this function to descend to a new level of recursion but return later to the previous list. These are acting as temporary working lists which calculate a value for each item of an original list and then copy the result into a final list once it is found.

    str("list_" + i) = []

    If i = 1, then I would like this line of code to create an empty list with the name "list_1" which I can proceed to interact with throughout my script.

    Instead I"m met with "SyntaxError: can"t assign to function call"

    By all means let me know if I"m not making any sense at all and I will do my best to convey my request.


    Highly advise against this but this achieves what you want depending on your use case:

    globals()["list_" + str(i)] = []

    for i in range(5):

    globals()["list_" + str(i)] = []






    Depending on your use case switch globals for locals and vice-versa.

    A better idea would be defaultdict

    from collections import defaultdict

    my_lists = defaultdict(list)

    Now you don"t have to initialize any list until you use it and every key comes with it"s value being a list already. For example:

    for i in range(5):

    my_lists["list_" + str(i)].append("foo")



    {"list_0": ["foo"],

    "list_1": ["foo"],

    "list_2": ["foo"],

    "list_3": ["foo"],

    "list_4": ["foo"]})

  • Python 判断一列表是否为空列表

    万次阅读 2019-07-31 14:36:02
    方法1(推荐):在Python中,False,0,’’,[],{}...方法3:让解释器再生成一个空列表,并将这个空列表与list_temp进行比较。此方法效率最低。 list_temp = [] print('方法1(推荐):在Python中,False,0,'',[],{},...
  • python3 判断列表是一个空列表

    万次阅读 2017-11-24 09:46:44
    python3 判断空列表@(python3)有判断列表是否为空的需求,试了好多方式,比如:a = [] if a is not None: COMMANDa = [] if a[0] is None: COMMAND各种乱七八糟的逻辑,老是无法满足。其实很简单。a = [] if a: ...
  • python创建空列表

    万次阅读 2017-11-12 23:45:30
    第一次写博客,请多多指教呀~写一函数创建一个空列表,参数为列表的大小,返回列表。def new(size): newlist = [] for i in range(0, size): newlist.append([]) return newlist 在命令行中执行
  • Python3 空列表添加数据

    千次阅读 2020-03-11 18:29:31
    Python3 空列表添加数据 Python3中空列表是不能直接调用append函数的,返回值会是None。 empty_list = [] print(empty_list.append(0)) 运行结果如下: 要向空列表中添加数据,“+”来组合列表: empty_list = [] ...
  • # 空列表创建方式、 lst1 = [] lst12 =list() #空字典创建方式 dicr1 = {} dictr = dict() # 空元祖创建方式 t9 = () t91 = tuple()
  • 主要介绍了Python创建空列表的字典2种方法详解,需要的朋友可以参考下
  • python:关于空列表的用法错误

    千次阅读 2019-12-19 21:42:54
    list =[] #定义一个空列表 #想把新建的列表创建为8元素且每元素为0的列表 for i in range(8): list[i] = 0 结果输出报错: Traceback (most recent call last): File "<stdin>", line 2, in <module...
  • 我们有时会需要一个空列表,用来在指定索引处赋值,比如我有一个空列表 L ,现在我需要直接在第7位置赋值(L[7]=666),而不是常规的顺序赋值(用append追加元素),这时要怎么生成这个空列表呢?方法很简单,代码...
  • Python中,一个空列表,空元组,空字符串,空字典的布尔值为False,但是不是None,具体如下所示: 如上所示,Python中判断一列表是否为空,切不可用是否None来判断,而应该直接判断,如if a,如果a为空列表,...
  • Python学习之空列表[]与None

    千次阅读 2018-11-07 14:48:49
    空列表也是列表,None类型只有None一值 >>> L1, L2 = None, [] >>> L1, L2 (None, []) >>> L1 == None True >>> L1 is None True >>> L2 == None False >>> L2 is None False >>> L2 == [] True
  • 这里
  • 定义 元组(tuple):  不可变序列,一旦建立不能修改元组中的元素。 列表[list]:  可变序列,可以添加和删除其中的元素。...空元组、空列表、空字典、空集合 >>> a=() >>> b=[] &
  • python 变量初始化空列表

    千次阅读 2018-11-21 17:33:27
    python 不能写new_loss=old_loss=[] 这样 两变量实际上是同一list 要分开写new_loss=[] Old_loss=[] 以下列数据文件为例: def analyze_mmr(fn): #初始化方法一 new_loss = [] old_loss = [] #初始化...
  • a,b,c,d,e,f,g 变量都赋值为空列表 传统: a=[] b=[] c=[] d=[] e=[] f=[] g=[] for循环: a,b,c,d,e,f,g=([] for i in range(7))
  • Python 将一个列表置为

    千次阅读 2019-07-31 13:41:23
    方法一:调用clear方法(推荐),在原有的列表中进行改动,开销较小。 方法二:引用赋值一个空列表,将原有的列表丢垃圾回收器,并创建一新列表,开销较大。
  • 1.list的创建: l = list() 或者: l = [] 2.list中元素的创建和表达 fruits = ['apple', 'banana', 'pear', 'grapes', 'pineapple', 'watermelon'] fruits[2] #从0开始数起,第三元素 pear 3....
  • Python 创建空列表的字典

    千次阅读 2015-09-08 10:35:21
    如果要创建一这样的字典,该怎么做?{1:[], 2:[], 3:[], 4:[]}下面对比两种方法的异同



1 2 3 4 5 ... 20
收藏数 207,599
精华内容 83,039


python 订阅