: List Function (Methods) And Additional Questions
M3-R5.1 · Chapter 5: Sequence Data Types · 21 min read
Consider a list:
company=["IBM","HCL","Wipro"]
|
No. |
Function Name |
Description |
Example |
|
|
1 |
append( ) |
To add element to the list at the end. Syntax: list-name.append (element) |
>>> company.append("Google") >>> company ['IBM', 'HCL', 'Wipro', 'Google'] |
|
|
Error: >>>company.append("infosys","microsoft") # takes exactly one element TypeError: append() takes exactly one argument (2 given) |
||||
|
2 |
extend( ) |
Add a list, to the end of the current list. Syntax: list-name.extend(list) |
>>>company=["IBM","HCL","Wipro"] >>> desktop=["dell","HP"] >>> company.extend(desktop) >>> company ['IBM', 'HCL', 'Wipro', 'dell', 'HP'] |
|
|
Error: >>>company.extend("dell","HP") #takes only a list as argument TypeError: extend() takes exactly one argument (2 given) |
||||
|
3. |
len( ) |
Find the length of the list. Syntax: len(list-name) |
>>>company=["IBM","HCL","Wipro"] >>> len(company) 3 >>> L=[3,6,[5,4]] >>> len(L) 3 |
|
|
4 |
index( ) |
Returns the index of the first element with the specified value. Syntax: list-name.index(element) |
>>> company = ["IBM", "HCL", "Wipro", "HCL","Wipro"] >>> company.index("Wipro") 2 |
|
|
Error: >>> company.index("WIPRO") # Python is case-sensitive language Value Error: 'WIPRO' is not in list >>> company.index(2) # Write the element, not index Value Error: 2 is not in list |
||||
|
5 |
insert( ) |
Adds an element at the specified position. Syntax: list.insert(index, element) |
>>>company=["IBM","HCL","Wipro"] >>> company.insert(2,"Apple") >>> company ['IBM', 'HCL', 'Apple', 'Wipro'] >>> company.insert(16,"Microsoft") >>> company ['IBM', 'HCL', 'Apple', 'Wipro', 'Microsoft'] >>> company.insert(-16,"TCS") >>> company ['TCS', 'IBM', 'HCL', 'Apple', 'Wipro', 'Microsoft'] |
|
|
6 |
count( ) |
Return the number of times the value appears. Syntax: list-name.count(element) |
>>> company = ["IBM", "HCL", "Wipro", "HCL","Wipro"] >>> company.count("HCL") 2 >>> company.count("TCS") 0 |
|
|
7 |
remove( ) |
To remove an element from the list. Syntax: list-name.remove(element) |
>>> company = ["IBM", "HCL", "Wipro", "HCL","Wipro"] >>> company.remove("Wipro") >>> company ['IBM', 'HCL', 'HCL', 'Wipro'] |
|
|
Error: >>> company.remove("Yahoo") ValueError: list.remove(x): x not in list |
||||
|
8 |
clear( ) |
Removes all the elements from list. Syntax: list-name.clear( ) |
>>> company=["IBM","HCL", "Wipro"] >>> company.clear( ) >>> company [ ] |
|
|
9 |
pop( ) |
Removes the element at the specified position and returns the deleted element. Syntax: list-name.pop(index) The index argument is optional. If no index is specified, pop( ) removes and returns the last item in the list. |
>>>company=["IBM","HCL", "Wipro"] >>> company.pop(1) 'HCL' >>> company ['IBM', 'Wipro'] >>> company.pop( ) 'Wipro' |
|
|
Error: >>>L=[ ] >>>L.pop( ) IndexError: pop from empty list |
||||
|
10 |
copy( ) |
Returns a copy of the list. Syntax: list-name.copy( ) |
>>>company=["IBM","HCL", "Wipro"] >>> L=company.copy( ) >>> L ['IBM', 'HCL', 'Wipro'] |
|
|
11 |
reverse( ) |
Reverses the order of the list. Syntax: list-name.reverse( ) Takes no argument, returns no list. |
>>>company=["IBM","HCL", "Wipro"] >>> company.reverse() >>> company ['Wipro', 'HCL', 'IBM'] |
|
|
12. |
sort( ) |
Sorts the list. By default in ascending order. Syntax: list-name.sort( ) |
>>>company=["IBM","HCL", "Wipro"] >>>company.sort( ) >>> company ['HCL', 'IBM', 'Wipro'] To sort a list in descending order: >>>company=["IBM","HCL", "Wipro"] >>> company.sort(reverse=True) >>> company ['Wipro', 'IBM', 'HCL'] |
|
Deleting the elements from the list using del statement:
Syntax:
del list-name[index] # to remove element at specified index
del list-name[start:end] # to remove elements in list slice
Example:
>>> L=[10,20,30,40,50]
>>> del L[2] # delete the element at the index 2
>>> L
[10, 20, 40, 50]
>>> L= [10,20,30,40,50]
>>> del L[1:3] # deletes elements of list from index 1 to 2.
>>> L
[10, 40, 50]
>>> del L # deletes all elements and the list object too.
>>> L
NameError: name 'L' is not defined
Difference between del, remove( ), pop( ), clear( ):
|
Sr. |
del |
remove( ) |
pop( ) |
clear( ) |
|
1 |
Statement |
Function |
Function |
Function |
|
2 |
Deletes a single element or a list slice or complete list. |
Removes the first matching item from the list. |
Removes an individual item and returns it. |
Removes all the elements from list. |
|
3 |
Removes all elements and deletes list object too. |
Removes all elements but list object still exists. |
||
|
Difference between append( ), extend( ) and insert( ) : |
||||
|
S. No. |
append( ) |
extend( ) |
insert( ) |
|
|
1 |
Adds single element in the end of the list. |
Add a list in the end of the another list |
Adds an element at the specified position. (Anywhere in the list) |
|
|
2 |
Takes one element as argument |
Takes one list as argument |
Takes two arguments, position and element. |
|
|
3 |
The length of the list will increase by 1. |
The length of the list will increase by the length of inserted list. |
The length of the list will increase by 1. |
|
: BASIC PROGRAMS FOR PRACTICE:
|
Q1: Sum of elements in a list nums = [1, 2, 3, 4, 5] total = sum(nums) print("Sum:", total) |
Find the largest number in a list nums = [4, 9, 1, 17, 3] larg = max(nums) print("Largest:", larg) |
|
Remove duplicates from a list nums = [1, 2, 2, 3, 4, 4, 5] unique = list(set(nums)) print("Unique elements:", unique) |
Sort a list in ascending order nums = [5, 3, 1, 4, 2] nums.sort() print("Sorted:", nums) |
|
Count occurrences of an element in a list nums = [1, 2, 3, 2, 2, 4] count = nums.count(2) print("Count of 2:", count) |
Reverse a list nums = [1, 2, 3, 4, 5] nums.reverse() print("Reversed:", nums) |
|
Simple Python Program to Find Sum of Even Numbers nums = [1, 2, 3, 4, 5, 6] even_sum = 0 for i in nums: if n % 2 == 0: even_sum += i print("Sum of even numbers:", even_sum) |
Find the Sum of All Numbers in a List nums = [1, 2, 3, 4, 5] total = 0 for n in nums: total += n print("Sum of all numbers:", total) |
|
Count Even Numbers in a List nums = [1, 2, 3, 4, 5, 6] count = 0 for n in nums: if n % 2 == 0: count += 1 print("Number of even numbers:", count) |
Find the Largest Number in a List nums = [10, 20, 5, 8] largest = nums[0] for n in nums: if n > largest: largest = n print("Largest number:", largest) |
|
Count Occurrences of a Given Number nums = [1, 2, 2, 3, 2, 4] target = 2 count = 0 for n in nums: if n == target: count += 1 print("Count of", target, ":", count) |
Reverse a List (Manually) nums = [1, 2, 3, 4] reversed_list = [] for i in range(len(nums)-1, -1, -1): reversed_list.append(nums[i]) print("Reversed list:", reversed_list) |
|
6. Find the Smallest Number in a List nums = [5, 3, 9, 1, 4] smallest = nums[0] for n in nums: if n < smallest: smallest = n print("Smallest number:", smallest) |
Count Odd Numbers in a List nums = [1, 2, 3, 4, 5, 6] count = 0 for n in nums: if n % 2 != 0: count += 1 print("Number of odd numbers:", count) |
|
Remove All Zeros from a List nums = [0, 1, 0, 2, 3, 0, 4] no_zeros = [] for n in nums: if n != 0: no_zeros.append(n) print("List without zeros:", no_zeros) |
Find Numbers Greater Than 5 nums = [2, 7, 3, 10, 1, 6] greater_than_5 = [] for n in nums: if n > 5: greater_than_5.append(n) print("Numbers greater than 5:", greater_than_5) |
|
Find All Duplicate Elements in a List nums = [1, 2, 3, 2, 4, 5, 1, 6] duplicates = [] for i in nums: if nums.count(i) > 1 and i not in duplicates: duplicates.append(i) print("Duplicates:", duplicates) |
Create a List of Squares of Even Numbers nums = [1, 2, 3, 4, 5, 6] squares = [] for n in nums: if n % 2 == 0: squares.append(n * n) print("Squares of even numbers:", squares) |
: INTERMEDIATE PROGRAMS FOR PRACTICE:
Program-1 Write a program to find the minimum and maximum number in a list.
|
L=eval(input("Enter a list of numbers")) # [4,7,9,10,45,21,46,67,23] --- input print("min=",min(L)) print("max=",max(L)) |
L=eval(input("Enter a list of numbers")) # [4,7,9,10,45,21,46,67,23] --- input max = L[0] # initialize with the first value min =L[0] # initialize with the first value for num in L: if num > max: max = num if num < min: min = num print("Largest:", max) # Output: Largest: 9 print("Smallest:", min) # Output: Smallest: 1 |
|
|
l1=eval(input("Enter the list1 of numbers")) l2=eval(input("Enter the list2 of numbers")) l3=eval(input("Enter the list3 of numbers")) # l1=[4,6 ,9,35,12,23,10] # l2=[0,9,29,56,23,56,18] # l3=[1,2,3,4,5,6,7,8,9,10] max_all = max(l1+l2+l3) min_all = min(l1+l2+l3) print ("The maximum of all 3 lists is : " + str(max_all)) print ("The minimum of all 3 lists is : " + str(min_all)) |
l= [12,78,89,76,32] m= l[0] for i in l: if i>m: m=i print(“The Greatest Element is :”,m) |
l=[12,78,89,76,32] m=l[0] for i in l: if i<m: m=i print(" the smallest element is:",m) |
|
Write a Python Program to Split a List in Half and Store the Elements in Two Different Lists List1 = [1,'ABC', 2, 3, 'abc', 'XYZ', 4] print("The first half of the list", List1[:3]) print("The second half of the list", List1[3:]) |
Write a Python Program to Remove Multiple Empty Strings From a List of Strings List1 = ['','ABC','xyz', '', 'abc', 'XYZ'] print("Original List:", str(List1)) while("" in List1) : List1.remove("") print("List after removing empty strings:", str(List1)) |
|
|
Write a Python Program to Interchange First and Last Elements of in a List List1 = ['XYZ1', 'ABC1', 'xyz2', 'abc2'] print("Original List:", str(List1)) List1[0], List1[-1] = List1[-1], List1[0] print("List after swapping:", str(List1)) |
Square Each Element of the List and Print List in Reverse Order List1=[1, 2, 3, 4, 5] print("Original list:",List1) for i in List1: # List1= [i**2 for i in List1] pp=i**2 print("Square elements:",pp) List1.reverse() print('Final List:', str(List1)) |
|
|
Write a program to increment the elements of a list with a number. lst = [ ] while True : num = int(input("Enter a number :- ")) lst.append(num) user = input("Do you want to quit enter yes =") if user == "yes": print(lst) break |
Write a program that input two lists and create a third, that contains all elements of the first followed by all elements of the second. a = eval(input ("Enter the first list =")) b = eval (input ("Enter the second list =")) print ("New list = ", a+b) |
|
|
Ask the user to enter a list containing numbers between 1 and 20 then replace all of the entries in the list that are greater than 10 with 10. a = [5,13,7,33,9,43,20,6] for i in range(len(a)) : if a[i] > 10 : a[i] = 10 print ("New list ",a) |
Ask the user to enter a list of string. Create a new list that consist of those strings with there first characters removed. lst = ["Shiv","Kashi","Portal","Express"] for i in range(len(lst)) : lst [ i ] = lst [ i ] [ 1:] print("New list = ",lst) |
|
|
Write a program to check if a number is present in the list or not. If the number is present, print the position of the number. Print an appropriate message if the number is not present in the list. lst = eval(input("Enter first list :-")) num = int(input("Enter the number which you want to search :-")) if num in lst : print(lst.index( num ) ) else : print("Number not found") |
Crate the following lists using a for loop: (a) A list consisting of the integers 0 through 49. (b) A list consisting the square of the integer 1 Till 50 (c) The list [“a”, “bb”, “ccc” , “dddd” ……….] that ends with 26 copies of the letter z. Ans:-a lst = [ ] for i in range(50): lst = lst + [ i ] print(lst) |
|
|
Ans:-b lst = [ ] for i in range(51): lst = lst + [ i**2 ] print(lst) |
Ans:-c lst = [ ] for i in range(1,27): lst = lst + [ chr(96+i) * i ] print(lst) |
|
|
Write a program that takes any two list l and m of the same size and adds their elements together to form a new list n whose element are sum of the corresponding elements in l and m. l = eval(input("Enter first list = ")) m = eval(input("Enter second list = ")) n = [ ] for i in range(len(l)): n = n + [ l [ i ] + m [ i ] ] print("New list = ",n) Output :- Enter first list = [1,2,3,4,5,6,7,8,9] Enter second list = [1,2,3,4,5,6,7,8,9] New list = [2, 4, 6, 8, 10, 12, 14, 16, 18] |
Write a program to move all duplicate values in a list to the end of the list. lst = [21,3,5,9,21,10,5,15,9,15] dup = [ ] n = 1 while n < len(lst): for i in lst : if lst.count( i ) != 1 : lst.remove( i ) dup.append(i) n += 1 lst.sort() print("New list :- ",lst + dup) |
|
|
Write a program to display the maximum and minimum values from the specified range of indexes of a list. lst = eval(input("Enter a list :-")) start = int(input("Enter starting index :-")) stop = int(input("Enter stoping index :-")) print( "Max :-", max( lst [ start : stop ] ) ) print("Min :- ", min( lst [ start : stop ] )) |
Write a program rotates the elements of a list show that the element at the first index moves to the second index ,the element i n second index moves to the third index, etc, and the element in the last index moves to the first index. lst = [3, 5, 6, 9, 10, 12, 15, 18, 20, 21] print ("New list =", [lst[ -1] ] + lst[0 : -1] ) |
|
|
Write a program to compare two equal sized lists and print the first index where they differ. lst1 = [1,2,3,4,5,6,7,8,9] lst2 = [1,3,2,4,5,6,7,8,9] for i in range(len(lst1)): if lst1[i] != lst2[i] : print("index = ",i) break |
Q10. Write a program that reads the n to display 9th term of Fibonacci series: the Fibonacci sequence work as follows: 0,1,1,2,3,5,8,13,21,34,… term = int (input ("Enter the number =")) fib = [0,1,1] for i in range(term - 2): fib = fib + [ fib [ i + 1] + fib [ i + 2 ] ] print("Fibonacci sequence :-",fib) print( fib [ term ] ) |
|
|
Exercise 3: Turn every item of a list into its square numbers = [1, 2, 3, 4, 5, 6, 7] # result list res = [] for i in numbers: # calculate square and add to the result list res.append(i * i) print(res) &&&&&&&&&&&&&& numbers = [1, 2, 3, 4, 5, 6, 7] res = [x * x for x in numbers] print(res) |
Exercise 4: Concatenate two lists in the following order list1 = ["Hello ", "take "] list2 = ["Dear", "Sir"] ['Hello Dear', 'Hello Sir', 'take Dear', 'take Sir'] Ans: list1 = ["Hello ", "take "] list2 = ["Dear", "Sir"] res = [x + y for x in list1 for y in list2] print(res) |
|
|
Remove empty strings from the list of strings list1 = ["Mike", "", "Emma", "Kelly", "", "Brad"] # remove None from list1 and convert result into list res = list(filter(None, list1)) print(res) |
Write a program to add item 7000 after 6000 in the following Python List list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40] # understand indexing # list1[0] = 10 # list1[1] = 20 # list1[2] = [300, 400, [5000, 6000], 500] # list1[2][2] = [5000, 6000] # list1[2][2][1] = 6000 # solution list1[2][2].append(7000) print(list1) |
|
|
Write a program to extend it by adding the sublist ["h", "i", "j"] in such a way that it will look like the following list. list1 = ["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"] sub_list = ["h", "i", "j"] # understand indexing # list1[2] = ['c', ['d', 'e', ['f', 'g'], 'k'], 'l'] # list1[2][1] = ['d', 'e', ['f', 'g'], 'k'] # list1[2][1][2] = ['f', 'g'] # solution list1[2][1][2].extend(sub_list) print(list1) |
Write a program to find value 20 in the list, and if it is present, replace it with 200. Only update the first occurrence of an item. list1 = [5, 10, 15, 20, 25, 50, 20] # get the first occurrence index index = list1.index(20) # update item present at location list1[index] = 200 print(list1) |
|
|
Write a program to remove all occurrences of item 20. list1 = [5, 20, 15, 20, 25, 50, 20] list1 = [5, 20, 15, 20, 25, 50, 20] # list comprehension # remove specific items and return a new list def remove_value(sample_list, val): return [i for i in sample_list if i != val] res = remove_value(list1, 20) print(res) 2222222222222222222222222222222222 list1 = [5, 20, 15, 20, 25, 50, 20] while 20 in list1: list1.remove(20) print(list1) |
Q: Program to search an element in a list. (Linear Search). L=eval(input("Enter the elements: ")) n=len(L) item=int(input("Enter the element that you want to search : ")) for i in range(n): if L[i]==item: print("Element found at the position :", i+1) break else: print("Element not Found") Output: Enter the elements: 56,78,98,23,11,77,44,23,65 Enter the element that you want to search : 23 Element found at the position : 4 |
|