Python Set Exercises: Practice for Set Manipulation

thumb_up 1  ·  sell Python set exercises, Set manipulation exercises in Python, Set manipulation practice in Python

Example 1

Python program to find common elements in two lists with the help of set operations −

 
l1=[1,2,3,4,5] l2=[4,5,6,7,8] s1=set(l1) s2=set(l2) commons = s1&s2 # or s1.intersection(s2) commonlist = list(commons) print (commonlist)

It will produce the following output −

[4, 5]

Example 2

Python program to check if a set is a subset of another −

 
s1={1,2,3,4,5} s2={4,5} if s2.issubset(s1): print ("s2 is a subset of s1") else: print ("s2 is not a subset of s1")

It will produce the following output −

s2 is a subset of s1

Example 3

Python program to obtain a list of unique elements in a list −

 
T1 = (1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2) s1 = set(T1) print (s1)

It will produce the following output −

{1, 2, 3, 4, 5, 6, 7, 8, 9}

Exercise Programs

  • Python program to find the size of a set object.

  • Python program that splits a set into two based on odd/even numbers.

  • Python program to remove all negative numbers from a set.

  • Python program to build another set with absolute value of each number in a set.

  • Python program to remove all strings from a set which has elements of different types.

 

 

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back