python中创建空列表_Python空列表教程–如何在Python中创建空列表

python中创建空列表

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

如果您想学习如何在Python中高效地创建一个空列表,那么本文适合您。

You will learn:

您将学习:

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

    如何使用方括号[]创建一个空列表。

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

    如何使用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)
0

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

空列表是虚假的值,这意味着它们在布尔上下文中的计算结果为False

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

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

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

您可以使用方法append()insert()将元素添加到空列表中:

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

    append()将元素添加到列表的末尾。

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

    insert()将元素添加到您选择的列表的特定索引处。

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")
else:
	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.

由于列表为空,因此其值为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):
	num.append(i)

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:

提示:我们通常使用append()将第一个元素添加到空列表中,但是您也可以使用索引0调用insert()方法添加此元素:

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

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

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

另外,您可以使用构造函数list()创建一个空列表,这将创建一个新的列表对象。

According to the Python Documentation:

根据Python文档

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)
0

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

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

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

例: (Example:)

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

这是一个功能齐全的列表,因此我们可以向其中添加元素:

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

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.

    我们通常使用list()从现有可迭代对象(如字符串,字典或元组list()创建列表。

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

    您通常会看到方括号[]用于在Python中创建空列表,因为此语法更简洁,更快捷。

🔸效率 (🔸 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.

让我们使用timeit模块检查它们的时间效率。

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

要在您的Python程序中使用此模块,您需要将其导入:

>>> 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)
0.0008467000000109692

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

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

💡 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

    []0.0008467000000109692

  • list(): 0.002867799999989984

    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
0.0020210999999790147

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

我敢肯定,您现在必须问这个问题:如果list()做的完全一样,为什么它们的效率比[]低?

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.

您可以使用一对空的方括号[]或类型构造函数list()来创建一个空列表,该内置函数可以在不传递任何参数时创建一个空列表。

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

方括号[]在Python中通常用于创建空列表,因为它更快,更简洁。

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/

python中创建空列表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值