Python List Examples

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

Python lists are a sequence of items. Python list data type is one of the most efficient and powerful ways to store sequences in Python programming language. Lists can be initialized with an iterable (or any other sequential data type) or by using square brackets [ ]. Lists allow for fast random access, making them very useful for looking up values at arbitrary positions.

Lists may also contain another list as their value which makes them more versatile than arrays. The new elements in a list are appended at the end; however, if you want to add an element before another element already stored in your list, use insert() method instead of append(). If you want to remove some elements from a list without affecting others, use del() statement after referencing it.

Loop through a list

list = [1, 2, 3, 4, 5]
for item in list:
	print(item)
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]
list.reverse()

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

Close