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: 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")