Unlike other programming languages, Python has several exciting ways to make things easier so that you can understand even complex things most simplistically. In this chapter, we will discuss a few exciting things you can do on Python Lists.
Exciting things you can do on Python Lists
Using Python Lists, you can perform several interesting operations in your programs. However, we have curated the easiest and most widely used things listed below.
- Find the number of occurrences of an element in a list?
- How to find common elements in two lists?
- Working with different datatypes in a list
Find the number of occurrences of an element in a list
Using the count() method in Python, you can count the number of times an element is present in a list. Let us also look at a program to find the number of times a number appears in a list.
#python program to check how many times a number
#appears in a list
def checksomething(lis):
"""This function receives a list
and returns number of times an
element appears in a list"""
lis2=[] #declare an empty list
for item in lis:
"""This for loop will append element from lis
to lis2 if the element in an iteration is not
present in lis2
The objective is to create another list with
only unique elements from the main list elements
"""
if item not in lis2:
lis2.append(item)
for item in lis2:
"""This for loop checks the number of times
an element from lis2 appears in the original list"""
n=lis.count(item)
if n==1:
print("{} appears {} time in the list".format(item,n))
elif n>=1:
print("{} appears {} times in the list".format(item,n))
else:
print("Thank you!")
#declares a list with elements
list1 = [4,2,2,2,1,1,3,3,4,5,5,5,7,8,9,10]
checksomething(list1) #pass list1 to checksomething function
Output
4 appears 2 times in the list
2 appears 3 times in the list
1 appears 2 times in the list
3 appears 2 times in the list
5 appears 3 times in the list
7 appears 1 time in the list
8 appears 1 time in the list
9 appears 1 time in the list
10 appears 1 time in the list
How to find common elements in two lists?
We can find common elements between two sets using the intersection() method. We can also use this concept to find the common elements between two lists. You cannot use the intersection() method directly on the lists, but you can convert the lists to sets, perform intersection and convert the result to a list in the output as mentioned in the program below.
#Python program to find
#common elements in two lists
def commoninlist(lis1,lis2):
"""This function takes two lists as parameters,
converts them into sets, so that intersection
can be performed to obtain the common elements.
The final set is again converted to a list"""
set1=set(lis1) #converts lis1 into a set, set1
set2=set(lis2) #converts lis2 into a set, set2
commonset=set1.intersection(set2) #finding common elements and storing into a new set, commonset
result_list=list(commonset) #converting the set, commonset into a list
result_list.sort() #sorting the list
print("The common elements are: ",result_list) #printing the output
list1=[11,22,33,44,77,88,99] #declare list1
list2=[12,33,55,77,88,99] #declare list2
commoninlist(list1,list2) #pass list1 and list2 to commonlist function
Output:
The common elements are: [33, 77, 88, 99]
This is one of the exciting things you can do on Python Lists.
Working with different datatypes in a list
One reason programmers always choose lists over arrays is the former’s feature to store different datatypes. You can store a string, an int, and a float very easily in a list and retrieve them whenever you want.
#Python program to store and retrieve
#different kinds of datatypes
def differentelements():
"""This function stores different vegetables,
their prices and discounts into a list and
finally retrieves one of them into output"""
n=int(input("How many vegetables do you want to enter?"))
veg_list=[]
for item in range(n):
"""This for loop stores vegetables to the
list, veg_list"""
print("Enter vegetable name: ",end=" ")
veg_list.append(input())
print("Enter price: ",end=" ")
veg_list.append(int(input()))
print("Enter max. discount: ",end=" ")
veg_list.append(float(input()))
print("The complete list with vegetable name: \n",veg_list)
#Let us now retrieve details of any one vegetable
veg_name=input("Please enter the vegetable name: ")
flag=True
while True:
if veg_name in veg_list:
for veg in range(len(veg_list)):
if veg_name==veg_list[veg]:
print("Vegetable name: {:s}, Price: {:d}, Max Discount: {:.2f}".format(veg_list[veg],veg_list[veg+1],veg_list[veg+2]))
break
else:
print("{} does not have the entered veg.".format(veg_list))
print("Please enter the exact veg name from the list: ")
veg_name=input()
continue
differentelements()
Output
How many vegetables do you want to enter?3
Enter vegetable name: Carrot
Enter price: 38
Enter max. discount: 1.5
Enter vegetable name: Spinach
Enter price: 39
Enter max. discount: 2.5
Enter vegetable name: Cucumber
Enter price: 40
Enter max. discount: 3.5
The complete list with vegetable name:
['Carrot', 38, 1.5, 'Spinach', 39, 2.5, 'Cucumber', 40, 3.5]
Please enter the vegetable name: Tomat
['Carrot', 38, 1.5, 'Spinach', 39, 2.5, 'Cucumber', 40, 3.5] does not have the entered veg.
Please enter the exact veg name from the list:
Tomato
['Carrot', 38, 1.5, 'Spinach', 39, 2.5, 'Cucumber', 40, 3.5] does not have the entered veg.
Please enter the exact veg name from the list:
Spinach
Vegetable name: Spinach, Price: 39, Max Discount: 2.50
From the output mentioned above, you can notice that we stored the details of three different vegetables into a list. We also tried retrieving the details of the vegetable, Spinach. When the vegetable, Tomato was entered, the command line window prompted us to enter the exact name again as Tomato is not present in the list.