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

Как проверить что массив пустой в python

  • автор:

Python isEmpty() equivalent – How to Check if a List is Empty in Python

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Python isEmpty() equivalent – How to Check if a List is Empty in Python

A list is one of the data structures in Python that you can use to store a collection of variables.

In some cases, you have to iterate through and perform an operation on the elements of a list. But you can’t loop/iterate through a list if it has no elements in it.

In this article, you’ll learn how to check if a list is empty by:

  • Using the not operator.
  • Using the len() function.
  • Comparing the list to an empty list.

How To Check if a List Is Empty in Python Using the not Operator

The not operator in Python is used for logical negation. Here’s an example:

not returns true when an operand is false, and false if an operand is true.

You can check if a collection is empty using the logic above. Here’s how:

In the code above, we used an if statement and the not operator to check if the people_list was empty.

How To Check if a List Is Empty in Python Using the len() Function

You can use the len() function in Python to return the number of elements in a data structure.

Here’s an example:

Using the len() function, we printed the length of the people_list list which had four elements.

You can also get the length of an empty list:

Now that we know that the length of an empty list is 0, we use it to check if a list is empty:

How To Check if a List Is Empty in Python By Comparing To an Empty List

An interesting way to check if a list is empty is by comparing it to another empty list. That is:

In the example above, we compared the people_list list to an empty list: if people_list == []

You can play around with the code by adding elements to the list to see which if. else statement gets executed.

Summary

In this article, we saw how to check if a list is empty in Python by using three different methods.

We saw how to check if a list is empty by using the not operator, and the len() function.

We also saw how check if a list is empty by comparing it to an empty list.

Как проверить что массив пустой в python

The Python List is a general data structure widely used in Python programs. They are found in other languages, often referred to as dynamic arrays. They are both mutable and a sequence data type that allows them to be indexed and sliced. The list can contain different types of objects, including other list objects.

# List methods and supported operators

Starting with a given list a :

Note that the append() method only appends one new element to the end of the list. If you append a list to another list, the list that you append becomes a single element at the end of the first list.

Lists can also be concatenated with the + operator. Note that this does not modify any of the original lists:

Lists can also be reversed when sorted using the reverse=True flag in the sort() method.

If you want to sort by attributes of items, you can use the key keyword argument:

In case of list of dicts the concept is the same:

Sort by sub dict :

Better way to sort using attrgetter and itemgetter

Lists can also be sorted using attrgetter and itemgetter functions from the operator module. These can help improve readability and reusability. Here are some examples,

itemgetter can also be given an index. This is helpful if you want to sort based on indices of a tuple.

Use the attrgetter if you want to sort by attributes of an object,

Take care doing this if your list contains references to objects (eg a list of lists), see Common Pitfalls — List multiplication and common references

If you want to create a copy of the list you have below options. You can slice it:

You can use the built in list() function:

You can use generic copy.copy():

This is a little slower than list() because it has to find out the datatype of old_list first. If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

Obviously the slowest and most memory-needing method, but sometimes unavoidable.

copy() – Returns a shallow copy of the list

# Accessing list values

Python lists are zero-indexed, and act like arrays in other languages.

Attempting to access an index outside the bounds of the list will raise an IndexError .

Negative indices are interpreted as counting from the end of the list.

This is functionally equivalent to

Lists allow to use slice notation as lst[start:end:step] . The output of the slice notation is a new list containing elements from index start to end-1 . If options are omitted start defaults to beginning of list, end to end of list and step to 1:

With this in mind, you can print a reversed version of the list by calling

When using step lengths of negative amounts, the starting index has to be greater than the ending index otherwise the result will be an empty list.

Using negative step indices are equivalent to the following code:

The indices used are 1 less than those used in negative indexing and are reversed.

Advanced slicing

When lists are sliced the __getitem__() method of the list object is called, with a slice object. Python has a builtin slice method to generate slice objects. We can use this to store a slice and reuse it later like so,

This can be of great use by providing slicing functionality to our objects by overriding __getitem__ in our class.

# Checking if list is empty

The emptiness of a list is associated to the boolean False , so you don’t have to check len(lst) == 0 , but just lst or not lst

# Iterating over a list

Python supports using a for loop directly on a list:

You can also get the position of each item at the same time:

The other way of iterating a list based on the index value:

Note that changing items in a list while iterating on it may have unexpected results:

In this last example, we deleted the first item at the first iteration, but that caused bar to be skipped.

# Checking whether an item is in a list

Python makes it very simple to check whether an item is in a list. Simply use the in operator.

Note: the in operator on sets is asymptotically faster than on lists. If you need to use it many times on potentially large lists, you may want to convert your list to a set , and test the presence of elements on the set .

# Any and All

You can use all() to determine if all the values in an iterable evaluate to True

Likewise, any() determines if one or more values in an iterable evaluate to True

While this example uses a list, it is important to note these built-ins work with any iterable, including generators.

# Length of a list

Use len() to get the one-dimensional length of a list.

len() also works on strings, dictionaries, and other data structures similar to lists.

Note that len() is a built-in function, not a method of a list object.

Also note that the cost of len() is O(1) , meaning it will take the same amount of time to get the length of a list regardless of its length.

# Reversing list elements

You can use the reversed function which returns an iterator to the reversed list:

Note that the list "numbers" remains unchanged by this operation, and remains in the same order it was originally.

To reverse in place, you can also use the reverse method

You can also reverse a list (actually obtaining a copy, the original list is unaffected) by using the slicing syntax, setting the third argument (the step) as -1:

# Concatenate and Merge lists

If the lists have different lengths then the result will include only as many elements as the shortest one:

For padding lists of unequal length to the longest one with None s use itertools.zip_longest ( itertools.izip_longest in Python 2)

# Remove duplicate values in list

Removing duplicate values in a list can be done by converting the list to a set (that is an unordered collection of distinct objects). If a list data structure is needed, then the set can be converted back to a list using the function list() :

Note that by converting a list to a set the original ordering is lost.

To preserve the order of the list one can use an OrderedDict

# Comparison of lists

It’s possible to compare lists and other sequences lexicographically using comparison operators. Both operands must be of the same type.

If one of the lists is contained at the start of the other, the shortest list wins.

# Accessing values in nested list

Starting with a three-dimensional list:

Accessing items in the list:

Performing support operations:

Using nested for loops to print the list:

Note that this operation can be used in a list comprehension or even as a generator to produce efficiencies, e.g.:

Not all items in the outer lists have to be lists themselves:

Another way to use nested for loops. The other way is better but I’ve needed to use this on occasion:

Using slices in nested list:

# Initializing a List to a Fixed Number of Elements

For immutable elements (e.g. None , string literals etc.):

For mutable elements, the same construct will result in all elements of the list referring to the same object, for example, for a set:

Instead, to initialize the list with a fixed number of different mutable objects, use:

# Syntax
  • [value, value, . ]
  • list([iterable])
# Remarks

list is a particular type of iterable, but it is not the only one that exists in Python. Sometimes it will be better to use set

list is the name given in Python to dynamic arrays (similar to vector<void*> from C++ or Java’s ArrayList<Object> ). It is not a linked-list.

Accessing elements is done in constant time and is very fast. Appending elements to the end of the list is amortized constant time, but once in a while it might involve allocation and copying of the whole list .

Python – Check if a list is empty or not

In Python programming, determining whether a list is empty holds importance for effective data handling. This article delves into concise techniques for checking the emptiness of a list, enabling developers to efficiently validate if a list contains elements or is devoid of data. Through clear code examples, learn how to implement these methods and bolster your proficiency in Python’s list management.

Example

How to Check if a List is Empty in Python

  • Using the len()
  • Using the implicit booleans
  • Using the PEP 8 recommended method
  • Using the != operator
  • Using the any() function
  • Using == operator
  • Using try/except
  • Using Numpy module

Check the Empty list using the len()

Let’s see how we can check whether a list is empty or not, in a less Pythonic way. We should avoid this way of explicitly checking for a sequence or list

Python3

Output:

Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the list

Check the empty list using the implicit Booleans

Now let’s see a more Pythonic way to check for an empty list. This method of check is an implicit way of checking and mor e preferable than the previous one .

Python3

Output:

Time complexity: O(n)
Auxiliary space: O(n), where n is the length of the list

Check the empty list using the PEP 8 recommended method

This is another method that allows us to determine whether a list in Python is empty. The most Pythonic method of checking the same is shown below.

Python3

Output:

Time complexity: O(1)
Auxiliary space: O(1)

Comparing a given list with an empty list using the != operator

The provided Python code checks whether the list lis1 is empty or not using an if statement. If the list is not empty, it prints “The list is not empty”; otherwise, it prints “Empty List.” This is achieved by comparing the list to an empty list using the inequality operator != . In this specific case, where lis1 is initialized as an empty list, the condition evaluates to false, resulting in the output “Empty List.”

Python3

Comparing given list with empty list using == operator

The subsequent if statement evaluates whether the lis1 is equal to an empty list, denoted by [] . If the condition is true, meaning the list is indeed empty, the program prints “Empty List” to the console. If the condition is false, indicating that the list is not empty, the program instead prints “The list is not empty.”

Python3

This approach has the advantage of being concise and easy to understand. It is also generally faster than other approaches that involve looping through the elements of the list.

Check the empty list using try/except

To check if a list is empty or not using try/except in Python, you can use the following algorithm:

Algorithm:

Initialize the list. Try to access the first element of the list using lst[0]. If the above step raises an IndexError exception, then the list is empty. Otherwise, the list is not empty. Handle the exception by printing “Empty List”.Here’s the Python code implementation of the above algorithm:

Efficiently Checking for an Empty List in Python

Frank Scholl

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.

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

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