If variable in list Python

Given an object, the task is to check whether the object is list or not.

Method #1: Using isinstance

ini_list1 = [1, 2, 3, 4, 5]

ini_list2 = '12345'

if isinstance[ini_list1, list]:

  print["your object is a list !"]

else:

    print["your object is not a list"]

if isinstance[ini_list2, list]:

    print["your object is a list"]

else:

    print["your object is not a list"]

Output: your object is a list ! your object is not a list

 
Method #2: Using type[x]

ini_list1 = [1, 2, 3, 4, 5]

ini_list2 = [12, 22, 33]

if type[ini_list1] is list:

    print["your object is a list"]

else:

    print["your object is not a list"]

if type[ini_list2] is list:

    print["your object is a list"]

else:

    print["your object is not a list"]

Output: your object is a list your object is not a list


Article Tags :

Practice Tags :

List is an important container in python as if stores elements of all the datatypes as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses one of the basic list operations of ways to check the existence of elements in the list. 
 

Method 1: Naive Method

In Naive method, one easily uses a loop that iterates through all the elements to check the existence of the target element. This is the simplest way to check the existence of the element in the list.
 

Method 2: Using in

Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list. List need not be sorted to practice this approach of checking.
 

Code #1: Demonstrating to check the existence of an element in the list using the Naive method and in .
 

test_list = [ 1, 6, 3, 5, 3, 4 ]

print["Checking if 4 exists in list [ using loop ] : "]

print["Checking if 4 exists in list [ using in ] : "]

Output : 
 



Checking if 4 exists in list [ using loop ] : Element Exists Checking if 4 exists in list [ using in ] : Element Exists

Method 3 : Using set[] + in

Converting the list into the set and then using in can possibly be more efficient than only using in. But having efficiency for a plus also has certain negatives. One among them is that the order of list is not preserved, and if you opt to take a new list for it, you would require to use extra space. Another drawback is that set disallows duplicity and hence duplicate elements would be removed from the original list.
 

Method 4 : Using sort[] + bisect_left[]

The conventional binary search way of testing element existence, hence list has to be sorted first and hence not preserving the element ordering. bisect_left[] returns the first occurrence of the element to be found and has worked similarly to lower_bound[] in C++ STL.

Note: The bisect function will only state the position of where to insert the element but not the details about if the element is present or not.
 

Code #2 : Demonstrating to check existence of element in list using set[] + in and sort[] + bisect_left[].
 

from bisect import bisect_left ,bisect

test_list_set = [ 1, 6, 3, 5, 3, 4 ]

test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]

print["Checking if 4 exists in list [ using set[] + in] : "]

test_list_set = set[test_list_set]

print["Checking if 4 exists in list [ using sort[] + bisect_left[] ] : "]

if bisect_left[test_list_bisect, 4]!=bisect[test_list_bisect, 4]:

    print["Element doesnt exist"]

Method 5 : Using count[]

We can use the in-built python List method, count[], to check if the passed element exists in List. If the passed element exists in the List, count[] method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

Code #3 : Demonstrating to check the existence of elements in the list using count[].

test_list = [10, 15, 20, 7, 46, 2808]

print["Checking if 15 exists in list"]

exist_count = test_list.count[15]

    print["Yes, 15 exists in list"]

    print["No, 15 does not exists in list"]


Article Tags :

Practice Tags :

I am fairly new to Python, and I was wondering if there was a succinct way of testing a value to see if it is one of the values in the list, similar to a SQL WHERE clause. Sorry if this is a basic question.

MsUpdate.UpdateClassificationTitle in [ 'Critical Updates', 'Feature Packs', 'Security Updates', 'Tools', 'Update Rollups', 'Updates', ]

i.e, I want to write:

if MsUpdate.UpdateClassificationTitle in [ 'Critical Updates', 'Feature Packs', 'Security Updates', 'Tools', 'Update Rollups', 'Updates' ]: then_do_something[]

Python is a dynamically typed language, and the variable data types are inferred without explicit intervention by the developer.

If we had code that needed a list but lacked type hints, which are optional, how can we avoid errors if the variable used is not a list?

In this tutorial, we'll take a look at how to check if a variable is a list in Python, using the type[] and isinstance[] functions, as well as the is operator:

Developers usually use type[] and is, though, these can be limited in certain contexts, in which case, it's better to use the isinstance[] function.

Check if Variable is a List with type[]

The built-in type[] function can be used to return the data type of an object. Let's create a Dictionary, Tuple and List and use the type[] function to check if a variable is a list or not:

grocery_list = ["milk", "cereal", "ice-cream"] aDict = {"username": "Daniel", "age": 27, "gender": "Male"} aTuple = ["apple", "banana", "cashew"] print["The type of grocery_list is ", type[grocery_list]] print["The type of aDict is ", type[aDict]] print["The type of aTuple is ", type[aTuple]]

This results in:

The type of grocery_list is The type of aDict is The type of aTuple is

Now, to alter code flow programatically, based on the results of this function:

a_list = [1, 2, 3, 4, 5] if type[a_list] == list: print["Variable is a list."] else: print["Variable is not a list."]

This results in:

"Variable is a list."

Check if Variable is a List with is Operator

The is operator is used to compare identities in Python. That is to say, it's used to check if two objects refer to the same location in memory.

The result of type[variable] will always point to the same memory location as the class of that variable. So, if we compare the results of the type[] function on our variable with the list class, it'll return True if our variable is a list.

Let's take a look at the is operator:

a_list = [1, 2, 3, 4, 5] print[type[a_list] is list]

This results in:

True

Since this might look off to some, let's do a sanity check for this approach, and compare the IDs of the objects in memory as well:

print["Memory address of 'list' class:", id[list]] print["Memory address of 'type[a_list]':", id[type[a_list]]]

Now, these should return the same number:

Memory address of 'list' class: 4363151680 Memory address of 'type[a_list]': 4363151680

Note: You'll need to keep any subtypes in mind if you've opted for this approach. If you compare the type[] result of any list sub-type, with the list class, it'll return False, even though the variable is-a list, although, a sub-class of it.

This shortfall of the is operator is fixed in the next approach - using the isinstance[] function.

Check if Variable is a List with isinstance[]

The isinstance[] function is another built-in function that allows you to check the data type of a variable. The function takes two arguments - the variable we're checking the type for, and the type we're looking for.

This function also takes sub-classes into consideration, so any list sub-classes will also return True for being an instance of the list.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Let's try this out with a regular list and a UserList from the collections framework:

from collections import UserList regular_list = [1, 2, 3, 4, 5] user_list = [6, 7, 8, 9, 10] if isinstance[regular_list, list]: print["'regular_list' is a list."] else: print["'regular_list' is not a list."] if isinstance[user_list, list]: print["'user_list' is a list."] else: print["'user_list' is not a list."]

Running this code results in:

'regular_list' is a list. 'user_list' is a list.

Conclusion

Python is a dynamically typed language, and sometimes, due to user-error, we might deal with an unexpected data type.

In this tutorial, we've gone over three ways to check if a variable is a list in Python - the type[] function, the is operator and isinstance[] function.

Video liên quan

Chủ Đề