4. Problem to find the length of a set

In the Python set program, we will find the length of a set and print it to see the total number of elements in that set with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Length of a set:

Steps to solve the program

1. Create a set using {}.
2. Add some elements to the set.
3. Find the length of set using the len() function.
4. Print the output.

				
					a = {1,2,3,5,6}
print("Original set: ",a)
print("Length of given set: ",len(a))
				
			

Output :

				
					Original set:  {1, 2, 3, 5, 6}
Length of given set:  5
				
			

remove an element from a set.

check if an element is present in a set.

3. Problem to remove an element from set

In this Python set program, we will remove an element from set and print the set to see the result with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Remove an element from set:

Steps to solve the program

1. Create a set using {}.
2. Add some elements in the set.
3. Remove an element from the set using remove() function.
4. Print the output.

				
					a = {1,2,3,5,6}
print("Original set: ",a)
a.remove(5)
print("New set: ",a)
				
			

Output :

				
					Original set:  {1, 2, 3, 5, 6}
New set:  {1, 2, 3, 6}
				
			

add an element to a set.

find the length of a set.

2. Problem to add elements to set in python

In this Python set program, we will add elements to set in Python and print the set to see the result with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.

Add elements to set:

Steps to solve the program
  1. Create a set using {}.
  2. Add some elements in the set.
  3. Add an element in the set using add() function.
  4. Print the output.
				
					a = {1,2,3,5,6}
print("Original set: ",a)
a.add(7)
print("New set: ",a)
				
			

Output :

				
					Original set:  {1, 2, 3, 5, 6}
New set:  {1, 2, 3, 5, 6, 7}
				
			

create a set with some elements.

remove an element from a set.

1. Problem to create a set in Python

In this Python set program, we will create a set in Python and add some elements in it as an example with the help of the below-given steps.

What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable, and has no duplicate elements.

Create a set in Python: 

Steps to solve the program
  1. Create a set using {}.
  2. Add some elements to the set.
  3. Print the set.
				
					a = {1,2,3,5,6}
print("Set: ",a)
				
			

Output :

				
					Set:  {1, 2, 3, 5, 6}
				
			

add an element to a set.

Python Set Programs, Exercises

Python set programs and exercises help beginners to get expertise in set data type, set is a collection of unique data enclosed with ‘{}’ curly braces. User can store only immutable data type to the set. e.g (int, float, string, tuple), mutable data type is not allowed as set element. e.g.  (list, dictionary, set), Let’s consider if we want to store student data, with unique id, then we can use set data type to store the data.

1). Python program to create a set with some elements.

2). Python program to add an element to a set.

3). Python program to remove an element from a set.

4). Python program to find the length of a set.

5). Python program to check if an element is present in a set.

6). Python program to find the union of two sets.

7). Python program to find the intersection of two sets.

8). Python program to find the difference of two sets.

9). Python program to find the symmetric difference of two sets.

10). Python program to show if one set is a subset of another set.

11). Python program to check if two sets are disjoint.

12). Python program to convert a list to a set.

13). Python program to convert a set to a list.

14). Python program to find the maximum element in a set.

15). Python program to find the minimum element in a set.

16). Python program to find the sum of elements in a set.

17). Python program to find the average of elements in a set.

18). Python program to check if all elements in a set are even.

19). Python program to check if all elements in a set are odd.

20). Python program to check if all elements in a set are prime.

21). Python program to check if a set is a proper subset of another set.

22). Python program to find the cartesian product of two sets.

23). Python program to find the power set of a set.

24). Python program to remove all elements from a set.

25). Python program to remove a random element from a set.

26). Python program to find the difference between two sets using the “-” operator.

27). Python program to find the intersection between two sets using the “&” operator.

28). Python program to find the union of multiple sets using the | operator.

29). Python program to find the symmetric difference of two sets using the “^” operator

30). Python program to check if a set is a superset of another set.

31). Python program to find the common elements between two sets.

32). Python program to remove a specific element from a set.

33). Python program to add multiple elements to a set.

34). Python program to remove multiple elements from a set.

35). Python program to check if a set is empty.

36). Python program to check if two sets are equal.

37). Python program to check if a set is a frozen set.

38). Python program to create a frozen set.

39). Python program to find the difference between multiple sets.

40). Python program to find the intersection between multiple sets.

41). Python program to check if any element in a set is a substring of a given string.

42). Python program to check if any element in a set is a prefix of a given string.

43). Python program to check if any element in a set is a suffix of a given string.

44). Python program to find the index of an element in a set.

45). Python program to convert a set to a dictionary with each element as key and value to an empty set.

46). Python program to create a set of even numbers from 1 to 20.

47). Python program to create a set of odd numbers from 1 to 20.

48). Python program to create a set of your favorite actors.

49). Python program to create a set of your favorite movies.

50). Python program to create two sets of books and find the intersection of sets.

51). Python program to find the longest word in a set.

Sort Lines of File with Python

Sort lines of file with Python is an easy way to arrange the file content in ascending order. In this article, we will focus to sort lines of file with the length of each line and sorting the lines in Alphabetical order.

Sort lines of file with line length size:

Let’s consider a text with the name sortcontent.txt which
contains some lines that we will try to sort on the basis of length of the each line.
				
					# sortcontent.txt
This is Python
Hello Good Morning How Are You.
This is Java
Python is good language

				
			
Steps to solve the program
  1. Open the first file using open(“sortcontent.txt”,”r”).
  2. Read all the lines of the file using readlines() method
  3. Now compare all lines one by one and exchange place
    of long length lines with small length lines to re-arrange them
    in ascending order using a nested loop.
  4. re-write all the lines of the list in ascending order.
				
					# Open file in read mode with context manager
with open("sortcontent.txt", "r") as file:
    # Read list of lines.
    FileLines = file.readlines()
    # Initial for loop to start picking each line one by one
    for i in range(len(FileLines)):
        # Initial for loop to compare all remaining line with previous one.
        for j in range(i+1, len(FileLines)):
            # compare each line length, swap small len line with long len line.
            if len(FileLines[i]) > len(FileLines[j]):
                temp = FileLines[i]
                FileLines[i] = FileLines[j]
                FileLines[j] = temp
            else:
                continue

# re-write all the line one by one to the file
with open('ReadContent.txt', "w") as file:
    # Combine all the sequentially arrange lines with join method.
    all_lines = ''.join(FileLines)
    # overwrite all the existing lines with new one
    file.write(all_lines)
				
			

Output: Open the sortcontent.txt file to see the output. below content will be available in the file. All lines of the file will arrange in ascending as per their length.

				
					This is Java
This is Python
Python is good language
Hello Good Morning How Are You.
				
			


Sort lines of file in Alphabetical order
:

Let’s consider a text file with a city name list, where names are mentioned one name in each line In the below program will sort the line of the file in alphabetical order, reads all the names from a file, and print them in alphabetical order.

				
					# cityname.txt
Kolkata
Mumbai
Pune
Bangalore
Delhi
				
			
				
					# open file with context manager
with open('cityname.txt') as file:
    # read all lines with readlines() method.
    file_lines = file.readlines()
    # sort line of file in alphabetical order
    file_lines.sort()
    # print all sorted name using loop
    for line in file_lines:
        print(line)
				
			

When we will run above program, will get following output.

				
					Bangalore
Delhi
Kolkata
Mumbai
Pune
				
			

Related Articles

display words from a file that has less than 5 characters.

Python file program to replace space by an underscore in a file

In this python file program, we will replace space by an underscore in a file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.

				
					#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.

				
			
Steps to solve the program
  1. Open the first file using open(“readcontent.txt”,”r”).
  2. Read the data in the file using read().
  3. Replace the space in the data with “_” using replace() and store the output in the new variable.
  4. Open the second file using open(“writecontent.txt”,”w”).
  5. Write the new data in the second file using write().
				
					# Open file in read mode
f1=open("readcontent.txt","r")
# Read data
data=f1.read()
# Replace space by underscore
data=data.replace(" ","_")
# Open file in write mode
f2=open("file2.txt","w")
# Write new data to file
f2.write(data)
				
			

Output: Open the writecontent.txt file to see the ouput.

My_name_is_john.
I’m_20_years_old.
I’m_learning_python_at_sqatools.
I’m_from_Australia.

 

 

display words from a file that has less than 5 characters.

Program to display words from a file that has less than 5 characters

In this python file program, we will display words from a file that has less than 5 characters with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.

				
					#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.

				
			
Steps to solve the program
  1. Open the file by using open(“readcontent.txt”).
  2. Where the file name is the name of the file.
  3. Read the data and split it into words using file.read().split().
  4. Use a for loop to iterate over the words.
  5. If the length of the word is less than 5 then print that word.
  6. Use an if statement for this purpose.
				
					# Open the file
file = open('readcontent.txt')
# Read data and converting it into words
words = file.read().split()
# Iterate over words
for word in words:
# Check for words having length less than 5
    if len(word)<5:
    # Print output
        print(word,end=" ")
				
			

Output:

My name is I’m 20 old. I’m at I’m from

 

 

remove all the lines that contain the character ‘t’ in a file and write it to another file.

replace space by an underscore in a file.

Program to remove specific line in a file and write it to another file

In this python file program, we will remove specific line in a file and write it to another file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.

				
					#readcontent.txt
My name is john.
I'm 20 years old.
I'm learning python at sqatools.
I'm from Australia.

				
			
Steps to solve the program
  1. Open the first file in the reading mode using open(‘readcontent.txt’,’r’).
  2. Open the second file in the append mode using open(‘writecontent.txt’,’a’).
  3. Read the lines of the file using readlines().
  4. Use a for loop to iterate over the lines.
  5. Using an if statement to check whether ‘t’ is in the line or not.
  6. If yes then add that line to the second file using write().
  7. Now close both files.
				
					# open file read mode
f1=open('readcontent.txt','r')
# open file in append mode
f2=open('writecontent.txt','a')
# Read lines from the file
lines=f1.readlines()
# Iterate over lines
for line in lines:
# Check for t in the lines
    if 't' in line:
    # Write lines to writecontent.txt file
        f2.write(line)
# Close the file
f1.close()
f2.close()
				
			

Output : Open writecontent.txt file to see the output.

I’m learning python at sqatools.
I’m from Australia.

 

 

count the total number of consonants in a file.

display words from a file that has less than 5 characters.

Program to count the total number of consonants in a file

In this python file program, we will count the total number of consonants in a file with the help of the below-given steps. Let’s consider we have readcontent.txt file with the below content.

				
					#readcontent.txt
Line1 : This is India.
Line2 : This is America.
Line3 : This is Canada.
Line4 : This is Australia.

				
			
Steps to solve the program
  1. Open the first file by using open(“readcontent.txt”).
  2. Read the data and split it into words using file.read().split().
  3. Create a list of vowels.
  4. Create a count variable and assign its value equal to 0.
  5. Use a for loop to iterate over the words.
  6. Use a nested for loop to iterate over the characters in the word.
  7. Check whether the character is not in the vowels list using an if statement.
  8. If yes then add 1 to the count variable.
  9. Print the output.
				
					# Open file
file = open('readcontent.txt')
# Read data and converting into words
words = file.read().split()
# Create a list of vowels
vowels = ['a','e','i','o','u','A','E','I','O','U']
# Create count variable
count = 0
# Iterate over words
for word in words:
# Iterate over characters in the word
    for char in word:
    # Check for consonants
        if char not in vowels:
    # Add 1 to the count variable for each consonant
            count += 1
# Print output
print("Total number of consonants in the file: ",count)
				
			

Output :

Total number of consonants in the file: 48

 

 

count the total number of vowels in a file.

remove all the lines that contain the character ‘t’ in a file and write it to another file.