Как проверить список на пустоту python
Перейти к содержимому

Как проверить список на пустоту python

  • автор:

How To Check If List Is Empty In Python?

Lists are the most commonly used data structures in python. It is used to store multiple items in a single object.

You can check if the list is empty using the len() function in python.

In this tutorial, you’ll learn how to check if the list is empty or not in python.

If you’re in Hurry

You can use the below code snippet to check if the list is empty in Python.

This is the recommended method in PEP-8 and it is the best way to check if the list is empty.

Snippet

Output

Snippet 2

Output

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to check if the list is empty or not in python.

To create an empty list with specific size, read How To Create An Empty List in Python with a Certain Size

Table of Contents

Using PEP-8 Recommended Method

You can check if the list is empty or not by using the list name in the If statement.

When you use the list in the IF statement, the length of the list is returned.

  • If the length is 0, it’s implicitly converted to False .
  • If the length is greater than 0, then it’s converted to True .

This method is also called Truth Value Testing.

Code

In the below example, you’re using the If not to check if the list is empty.
So you can implement the logic that needs to be executed when the list is empty in the If part.

Output

Snippet

In the below example, you’re using only the If to check if the list is empty.
So you can implement the logic that needs to be executed when the list is not empty in the If part.

Output

This is the fastest way to check if the list is empty in python.

Using The bool() Function

You can check if the list is empty in python using the bool() function.

bool() function returns boolean value of the specified object.

The object will always return True , unless the object is empty, like [] , () , <> .

You can use the bool() function for any of the list-like objects.

Snippet

Use the below code snippet to check if the list is empty or not using the bool() function.

Output

Snippet

Output

This is how you can use the bool() function to check if the list is empty or not in Python.

Using len() Function

In this section, you’ll learn how to use the len() function to check if the list is empty or not in python.

len() function returns the number of items in the list.

  • When the list is empty, the len() function returns 0 , and the 0 is implicitly converted to False when used in the If statement.
  • When the list is NOT empty, It returns the length value. Values other than 0 are converted to True implicitly.

Snippet

Use the below snippet to check if the list is empty or not in python using the len() function and If not .

Output

You can use the len() function alone to check if the list is not empty before performing any operation.

Snippet

Output

This is how you check if the list is empty or not in python using the len() function.

Using len() With Comparison Operator

You can use the len() function with the comparison operator and compare the result with 0 to check if the list is empty.

If the list is empty, then the If statement will be executed.

Snippet

Output

This is how you can use the len() function with the comparison operator to check if the list is empty or not in python.

Comparison With Empty List

You can also compare the list object with the empty list to check if the list is empty.

An empty list is denoted using the [] . When a list object is compared with [] using == operator, then it returns True if the list object is empty. Else it returns False .

Use the below snippet to check if the list is empty by comparing it with the empty list.

Snippet

Output

This is how you can use compare the list with the empty list to check if it’s empty or not.

Why You need to check If List is Empty

If you’re just checking if the list is empty or not Just to ensure it’s not empty before performing any operation, then you can pretty well use the list in the for loop or any other iterators directly. It’ll be executed only if the list has any items. Otherwise, it will not be executed.

Snippet

Conclusion

To summarize, you’ve learned how to check if a list is empty or not using the pep8 recommended method. It is the fastest way and the best way to check if the list is empty. You’ve also learned other methods available to check if the list is empty such as bool() function, len() function, compared with the empty list, and so on.

Efficiently Checking for an Empty List in Python

I stumbled on a story on Medium that detailed three different ways to check for an empty list in Python. While the information provided is technically correct, I felt the resolution of method choice left something to be desired. Notably, it doesn’t indicate the preferred method noted by the language developers or account for code formatting standards. With all of that considered, there is a best method of checking for an empty list in Python, and I can prove it.

Methods of Comparison

I’ll use the same three methods from the source since they are the most common methods considered: comparing to an empty list, checking the length, and using an implicit boolean conversion.

How Python Interprets These Comparisons

As you may already know, Python first converts lexical text into bytecode before the interpreter executes it. Using Python’s dis module, we can look at the bytecode generated for each method and examine how they really work.

This is confusing if you’ve never looked at bytecode before. The number on the far left is the line number corresponding to the lexical function code. Line 1 is the method definition, so it lacks any bytecode in this analysis. Note that for all of the methods above, lines 3 and 4 are identical, so we’ll focus only on line 2.

Explicit List

Four operations occur:

  • LOAD_FAST finds our variable a in memory puts it on the top of the stack.
  • BUILD_LIST allocates a new list in memory with a length of 0 and adds it to the top of the stack.
  • COMPARE_OP takes the top 2 items off the top of the stack and checks to see if they are equal. The way lists are compared to see if they are equal in python is by iterating through both lists and verifying that each element is equal. The result is placed on the top of the stack.
  • POP_JUMP_IF_FALSE takes the first element off the top of the stack and jumps to the indicated byte number if the value is false.

Of the three methods, this is the most complex way to check for a list being empty. It creates new objects in memory that garbage collection needs to later remove, and it invokes a loop through the lists for element comparison.

Explicit Length

For this method, six operations occur:

  • LOAD_GLOBAL finds the definition of len and adds it to the top of the stack.
  • LOAD_FAST, again, finds our variable a and adds it to the top of the stack.
  • CALL_FUNCTION grabs 1 parameter of the stack and then calls the next element on the stack passing that variable (i.e. it will pop a and pass it to len). The result of the function is then placed on the top of the stack.
  • LOAD_CONST puts a constant 0 on the top of the stack.
  • COMPARE_OP works the same as before and compares the result of len to the constant 0.
  • POP_JUMP_IF_FALSE works exactly the same.

This method isn’t bad. It is simple, readable, and requires minimal memory operations, but the operation takes place entirely in Python.

Implicit Boolean

Just two operations here:

  • LOAD_FAST puts a on the top of the stack.
  • POP_JUMP_IF_FALSE removes the top value and jumps ahead if it is false.

This method makes the others look bloated. It is very efficient and clearly shows the language was designed to function with implicit boolean conversion.

This seems too much like magic. What’s really happening here?

When the bytecode is interpreted at runtime the POP_JUMP_IF_FALSE examines the object in C and gets an appropriate boolean value based on the object. That means whatever is done behind the scenes has native support in C for determining if the list is empty. If you look into the source code of Python, you’ll find that the comparison is looking at the C object’s size property and returning True if it is greater than 0 or False if it isn’t. Thus, it is a streamlined implementation of the explicit length method implemented by the list object in C.

Don’t Just Take My Word For It

Final Thoughts

Empirically, the best way to check for an empty list in Python is by implicit boolean conversion. Does there exist a case or two where the length method is more readable? Sure, but such cases are very rare.

Как проверить, пустой ли список в Python

Чтобы проверить, пуст ли список в Python, вы можете написать условие, если длина списка равна нулю. Или вы можете напрямую использовать ссылку на список вместе с оператором not в качестве условия в операторе if.

Ниже приводится синтаксис для использования оператора not и список в качестве условия для проверки того, является ли список пустым.

В приведенном выше операторе If операторы внутри блока выполняются только в том случае, если myList не пуст.

Ниже приводится синтаксис использования длины списка для формирования условия проверки того, является ли список пустым.

Если список пуст, то в нем будет ноль элементов. Используйте встроенную функцию len() и передайте список в качестве аргумента. Функция возвращает целое число, представляющее количество элементов в списке. Если список пуст, len() возвращает 0, а условие len (myList) == 0 становится истинным.

Пример 1

В следующей программе мы инициализируем пустой список и программно проверяем, является ли список пустым или нет, используя оператор not и ссылку на список.

Пример 2

В следующей программе мы инициализируем пустой список и программно проверяем, является ли список пустым или нет, с помощью функции len().

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Как проверить, пуст ли список в Python

Введение Списки — одна из четырех наиболее часто используемых структур данных, предоставляемых Python. Его функциональность, расширяемость и простота использования делают его полезным для реализации различных типов функций. Списки Python имеют несколько интересных характеристик: 1. Изменяемость — это означает, что они могут изменяться, что означает, что они позволяют нам легко добавлять и удалять записи из них. В этом основное различие между списками Python и кортежами 2. Итеративность — это означает, что мы можем перебирать их (

Время чтения: 4 мин.

Вступление

Списки — одна из четырех наиболее часто используемых структур данных, предоставляемых Python. Его функциональность, расширяемость и простота использования делают его полезным для реализации различных типов функций.

Списки Python имеют несколько интересных характеристик:

  1. Изменяемость — это означает, что он может изменяться, что означает, что он позволяет нам легко добавлять и удалять записи из него. Это основное различие между списками Python и кортежами.
  2. Итеративность — это означает, что мы можем перебирать его (проходить все элементы в списке по порядку)

Главный атрибут, на котором мы остановимся, — это итеративность . Важная часть при работе с итерируемым объектом, в данном случае списком,

  • это проверка, есть ли что-нибудь для перебора. При неправильном обращении это может привести к множеству нежелательных ошибок.

Python предоставляет различные способы проверить, является ли наш список пустым или нет, некоторые неявные и некоторые явные, и в этой статье мы рассмотрим, как проверить, пуст ли список Python .

Использование функции len()

Один из способов — использовать len() чтобы проверить, пуст ли наш список:

Когда len(py_list) он производит ноль, который затем неявно приводится к логическому значению False . Таким образом, в случае пустого списка программа будет перенаправлена в блок else.

Хотя этот метод выглядит простым, для новичков он не такой интуитивно понятный.

Использование len () с оператором сравнения

Этот метод аналогичен описанному выше, но он более понятен и понятен. Вот почему те, кто плохо знаком с Python или с кодированием, обычно считают его более интуитивным:

В приведенном выше коде len(py_list) == 0 будет истинным, если список пуст, и будет перенаправлен в блок else. Это также позволяет вам устанавливать другие значения, а не полагаться на преобразование 0 False . Все остальные положительные значения преобразуются в True .

Сравнение с пустым списком

Этот метод также очень прост и хорошо работает для новичков, поскольку предполагает сравнение с пустым списком:

Здесь мы снова используем операцию сравнения для сравнения одного списка с другим — я пуст, и если оба пусты, будет выполняться блок if

Рекомендуемый стиль Pep-8

Для этого давайте взглянем на проверку истинности . В официальных документах указано, что:

  • константы, определенные как ложные: None и False.
  • ноль любого числового типа: 0, 0,0, 0j, десятичный (0), дробный (0, 1)
  • пустые последовательности и коллекции: », (), [], <>, set (), range (0)

Поскольку пустой список на самом деле является просто пустой коллекцией, он будет преобразован в логическое значение False . Следовательно, если py_list пуст, он будет преобразован в False .

Второй оператор очень похож, за исключением того, что он not изменит ложное условие на истинное. Этот подход очень похож на подход if(len(list)) .

Это предпочтительный подход, так как это самое чистое и кратчайшее решение.

Использование функции bool ()

Мы также можем использовать bool() чтобы проверить, что список пуст:

По сути, это тест истинности, реализованный вручную. Поэтому, если список не пуст, функция вернет True и если блок будет выполнен.

Этот подход менее распространен, поскольку мы можем достичь желаемых результатов даже без использования bool() , но неплохо знать, как Python работает под капотом.

Заключение

Эта статья была посвящена способам проверить, пуст ли наш список Python. Мы начали с изучения различных техник и, наконец, рассмотрели некоторые параметры, которые мы можем использовать, чтобы сделать свое суждение о том, какой метод может работать для нас.

Я не могу сказать, что это конец, поскольку новые обновления Python могут привести к появлению новых и более совершенных стилей кодирования. Так что лучше продолжать изучать и учиться.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *