Python List Operations
Learn List operation with below examples.
Get Vinodharanie Sivalingam’s stories in your inbox
Join Medium for free to get updates from this writer.
Create a List
Write a program to create a list of 5 integers the user enters.
def createList() -> []:
x = []
for i in range(5):
x.append(int(input("Enter a number")))
return xAccess Elements
Write a program to access and print a list's first, middle, and last elements.
def accessElement():
x = [12,3,4,56,7,8,5]
print(x[0])
print(x[len(x)//2])
print(x[len(x) - 1])Find the Length
def findLength(lst : []) -> int :
return len(lst)Sum of Elements
def sumOfElement(lst : []) -> int :
count = 0
for l in lst :
count += l
return countFind the Largest Number
def findLargeNumber(lst:[]) -> int:
largeNumber = lst[0]
for l in lst :
if largeNumber < l :
largeNumber = l
return largeNumberReverse a List
def reverseList(lst:[]) -> []:
reverseList = lst[:] # Deep copy
for (index, l) in enumerate(lst) :
reverseList[-1 * (index+1)] = l
return reverseList
#OR
def reverseList(lst:[]) -> []:
return lst[::-1]Filter Even Numbers
def filterEvenNumbers(lst: []) -> []:
evenNumberList = []
for i in lst :
if i%2 == 0 :
evenNumberList.append(i)
return evenNumberListCount Occurrences
def countOccurrences(lst:[], num:int) -> int:
return lst.count(num)Remove Duplicates
def removeDup(lst : []) -> []:
return list(set(lst))
#OR
def removeDup(lst : []) -> []:
removeDup = []
for l in lst:
if l not in removeDup:
removeDup.append(l)
return removeDup
#OR
def removeDup(lst : []) -> []:
return list(dict.fromkeys(lst))List Slicing
Write a program to extract the first half of a list and print it.
def listSlicing(lst: list) -> list:
return lst[:len(lst) // 2] # Use floor division `//` Concatenate Two Lists
def concatenateList(lst1:list, lst2:list) -> list:
lst1.extend(lst2)
return lst1
#OR
def concatenateList(lst1:list, lst2:list) -> list:
return lst1 + lst2Sort a List
def sortList(lst : list) -> list :
lst.sort()
return lst
#OR
def sortList(lst : list) -> list :
return sorted(lst)






