Python List Examples

In Python programming language List is a collection which is ordered and changeable. It allows duplicate members.

Loop through a list

list = [1, 2, 3, 4, 5]
for item in list:
sub_list = list[2:4] # [3,4,5]

Reverse a list

There are several methods to reverse an array in Python. These 2 methods are easy to follow.

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

reverse = list[::-1]

Remove duplicates in a list

The first approach is to convert a list to dictionary.

dict.fromkeys() method to create a dictionary from a list and it removes duplicates (same keys in dictionary’s case) automatically. Then we use list() method to convert a dictionary back to a list.

l = ['A', 'B', 'C', 'C', 'E', 'A']

l = list(dict.fromkeys(l))

The 2nd approach is to convert a list to a set using set() method. Set doesn’t allow duplicated values.

l = list(set(l))

Check if a given object is list or not

The isinstance() function is a method to check whether a specified object is of the specified type.

myList = [1, 2, 3]
if isinstance(myList, list): 
	print("myList is a list !") 
	print("myList is not a list") 

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.