Some Basic Python List Programs-3


Python program to remove duplicates from a list

list1 = [2, 6, 9, 8, 4, 8, 6, 6, 5, 7, 2, 4]

#using list comprehension
list2 = [] 
[list2.append(ele) for ele in list1 if ele not in list2] 
print(list2) 
#Output: [2, 6, 9, 8, 4, 5, 7]

#using list comprehension and enumerate()
list3 = [ele for i,ele in enumerate(list1) if ele not in list1[:i]]
print(list3) 
#Output: [2, 6, 9, 8, 4, 5, 7] 

#using set() 
list4 = list(set(list1))
print(list4)
#Output: [2, 4, 5, 6, 7, 8, 9]
  • List comprehension is a compact method that defines a list and its contents at the same time. The basic syntax of list comprehension consists of a square bracket with an expression that is executed for each element along with for loop to iterate over each element. Read more: List Comprehension in Python – Explained with Examples
  • The append() built-in list method adds the element of the iterable passed as an argument to the end of the list.
  • The built-in enumerate() function assigns an index to each element in an iterable and each time returns a tuple of the form (index, element). Read more: What is indexing, iterating and enumerating in python?
  • Slicing extracts a subset of elements from a sequence. It mainly uses three parameters strat, stop, and step enclosed in square brackets []. Read more: Slicing in python
  • The set() built-in method creates a set of the iterable passed. A set is an unordered collection of immutable and unique elements in python.
  • The list() built-in method takes an iterable and creates a new list of its elements.

Python program to check if one list is a subset of another list

list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [5, 8, 6, 4]

#using all()
if all(ele in list1 for ele in list2):
    print(f"{list2} is a sublist of {list1}")
else:
    print(f"{list2} is not a sublist of {list1}") 
#Output: [5, 8, 6, 4] is a sublist of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#using issubset() 
if set(list2).issubset(set(list1)):
    print(f"{list2} is a sublist of {list1}") 
else:
    print(f"{list2} is not a sublist of {list1}") 
#Output: [5, 8, 6, 4] is a sublist of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#using & operator
if set(list2) & set(list1) == set(list2):
    print(f"{list2} is a sublist of {list1}") 
else:
    print(f"{list2} is not a sublist of {list1}") 
#Output: [5, 8, 6, 4] is a sublist of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • The all() built-in method returns True If all the elements in the iterable passed are true else it returns False.
  • Python treats everything as an object and objects are always true in python. However, null values, None, 0, empty data types are observed as false in python.
  • The format() built-in string method returns a formatted representation of the string controlled by the format specifier. The prefix f before a string tells Python that the string is a format string. The replacement fields are expressions enclosed in curly brackets in a format string. They are evaluated at run time and then formatted.
  • The issubset() built-in method returns True if all the elements of a set are present in the iterable passed else it returns False.
  • A set in python represents a mathematical notion of a set and performs set operations like union, intersection, difference, etc. The ‘&’ operator executes the intersection between sets. Read more: Set Data Type in Python

Python program to check if all elements in a List are same

list = ['Python', 'Python', 'Python', 'Python', 'Python', 'Python']

#using all()
if all(ele == list[0] for ele in list):
    print("All the elements in the list are same")
else:
    print("All the elements in the list are different")
#Output: All the elements in the list are same

#using count() 
if list.count(list[0]) == len(list):
    print("All the elements in the list are same") 
else: 
    print("All the elements in the list are different")
#Output: All the elements in the list are same

#using set()
if len(set(list)) == 1:
    print("All the elements in the list are same") 
else: 
    print("All the elements in the list are different")
#Output: All the elements in the list are same
  • The count() built-in list method returns the number of times a specified element appears in the list.

Python program to insert a given string at the beginning of all elements in a list

list1 = [1, 2, 3, 4, 5]
str1 = 'number'

#using list comprehension and format()
str2 = str1 + '{}'
list2 = [str2.format(ele) for ele in list1]
print(list2)
#Output: ['number1', 'number2', 'number3', 'number4', 'number5']

#using list comprehension and % operator
str3 = str1 + '% s'
list3 = [str3 % ele for ele in list1]
print(list3)
#Output: ['number1', 'number2', 'number3', 'number4', 'number5']

#using map() and format()
str4 = str1 + '{}'
list4 = list(map(str4.format, list1))
print(list4)
#Output: ['number1', 'number2', 'number3', 'number4', 'number5']
  • The % operator is a format place holder for C-style formatting in a string. The “s” after the “%” signifies that the variable inserting in that position is of the string type.
  • The built-in map() function applies a given function to each element of an iterable and returns a list of the results.

Python program to pair consecutive elements in a list

list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#using list comprehension
list2 = [[list1[i], list1[i+1]] for i in range(len(list1)-1)]
print(list2)
#Output: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

#using zip()
list3 = list(zip(list1, list1[1:]))
print(list3)
#Output: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
  • The zip() built-in method returns an iterator of tuples, grouping the similar index of multiple sequences so that they can be used as a single entity.

Related Posts-

Leave a Comment

%d bloggers like this:
Python4U
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.