List Programs in Python: Important for O Level Exam

List Programs in Python

List Programs in Python: A list is a collection of different kinds of values or items. Since Python lists are mutable, we can change their elements after forming them. The comma (,) and the square brackets [enclose the list’s items] serve as separators.

1. Write a program to add an element to a list.

Description: You can use the append() method to add an element at the end of the list.

CODE
mylist=["Mango","Apple"]
mylist.append("Banana")
print("Add elements to a list","=",mylist)
OUTPUT
List Programs in Python
2. Write a program to remove an element from a list.

Description: You can use the remove() method to remove an element by value or the pop() method to remove by index.

CODE
mylist=["Mango","Apple","Banana"]
mylist.remove("Banana")
print("Remove an element from a list","=",mylist)
OUTPUT
List Programs in Python
3. Write a program to find the length of a list.

Description: Use the len() function to find the length of a list.

CODE
mylist=[1,2,3]
print("Length of a list","=",len(mylist))
OUTPUT
List Programs in Python
4. Write a program to check if an element exists in a list.

Description: Use the keyword to check if an element exists in a list.

CODE
mylist=[29,27,92,26,25]
print("Elements exists in a list","=",29 in mylist)
OUTPUT
List Programs in Python
5. Write a program to slice a list.

Description: You can slice a list by specifying the start, stop, and step values.

CODE
mylist=[1,2,3,4,5,6,7,8,9,10]
print("Slice in a list","=",mylist[2:10:2])
OUTPUT
List Programs in Python

For Loop Programs in Python

6. Write a program to sort a list.

Description: Use the sort() method to sort a list in ascending order.

CODE
mylist=[2,45,33,66,78,98,]
print("Sort in a list","=",mylist)
OUTPUT
List Programs in Python
7. Write a program to reverse a list.

Description: Use the reverse() method to reverse the elements of a list.

CODE
mylist=[2,45,33,66,78,98,]
mylist.reverse()
print("Reverse a list","=",mylist)
OUTPUT
List Programs in Python
8. Write a program to join a list.

Description: Use the + operator to concatenate two lists.

CODE
list1=[2,3]
list2=[4,5]
print("Join two lists","=",list1+list2)
OUTPUT
List Programs in Python
9. Write a program to copy a list.

Description: Use the copy() method or slicing to copy a list.

CODE
mylist=["Summer","Winter","Rainy","Spring"]
newlist=mylist.copy()
print("Copy a list","=",newlist)
OUTPUT
List Programs in Python
10. Write a program to count occurrences of an element in a list.

Description: Use the count() method to count the occurrences of an element.

CODE
mylist=[1,2,322,122,1,21,1,98,1,982,1]
print("Count occurrences of an element in a list","=", mylist.count(1))
OUTPUT
List Programs in Python
Share your love
Sleepy Expert
Sleepy Expert
Articles: 26

Leave a Reply

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