Python - Remove sublist that exists within another sublist
Python is a widely used software that has many different purposes and multiple functions to perform different tasks. One useful feature of python is list functionality which helps in collecting and storing different data but many times users face problem while deleting a sublist that already exists within another sublist. So, in this article, we will learn how to delete different sublists that already exist in other sublists.
To understand the problem clearly, let's take an example where we have to delete a sublist whose data already exists in another sublist.
Example
duplicate_list = [[Aayush, Shyam, John], [Shyam, John], [Henry, Joe], [David, Stefen, Damon], [David, Stefen]] #All the sublist whose data is already present in other sublist are to be removed
Output
The sublists named [Shyam,John] and [David,Stefan] already have the same data in other sublists, so these extra sublists will be deleted. The output should look like this:
new_list = [[Aayush, Shyam, John], [Henry, Joe], [David, Stefen, Damon]]
Now we will understand the different ways to delete a sublist that already exists in a sublist.
Here we have mentioned different possible methods:
List comprehension
The easiest way to delete all sublists present in other sublists is with the help of list comprehension. Check all sublists that exist in the list and copy those that do not exist in any other sublist to the new list. Let’s take an example to understand more clearly:
Example
duplicate_list = [[Aayush, Shyam, John], [Shyam, John], [Henry, Joe], [David, Stefen, Damon], [David, Stefen]] New_list = [sublist for sublist in duplicate_list if not any(set(sublist) <= set(other) for other in duplicate_list if sublist is not other)] #We first check all the lists of the duplicate list through the any() function and then we check for any repeatation with the help of <= operator
Output
After the code is completed, we will print the output of the above code. The output of the above code is as follows:
[[Aayush, Shyam, John], [Henry, Joe], [David, Stefen, Damon]]
All extra sublists are removed, so we wrote the correct code to remove sublists that are already in the sublist.
Define function
Another way to solve the problem is to create a completely new separate function to filter out all sublists that exist within other sublists. This can be done by defining a condition for the function and making it run accordingly.
Example
def is_sublist(sublist, other): #is_sublist is the function defined return set(sublist) <= set(other) #the functions checks 2 sublists at a time and if the sublist already exists then it returns with `true` feedback and does not consider the extra sublist duplicate_list = [[Aayush, Shyam, John], [Shyam, John], [Henry, Joe], [David, Stefen, Damon], [David, Stefen]] new_list = [sublist for sublist in duplicate_list if not any(is_sublist(sublist, other) for other in duplicate_list if sublist is not other)]
Output
The output of the above code is as follows:
[[Aayush, Shyam, John], [Henry, Joe], [David, Stefen, Damon]]
All extra sublists are removed, so we wrote the correct code to remove all extra sublists.
Compare each list
This is a very complex method for removing a sublist that already exists within another sublist. In this method, all sublists are compared with each other and the non-duplicate sublists are copied to a new list. We can understand this with the help of the following example:
Example
duplicate_list = [[Aayush, Shyam, John], [Shyam, John], [Henry, Joe], [David, Stefen, Damon], [David, Stefen]] #A copy of duplicate list is created to avoid any errors in the original file new_list = duplicate_list[:] #Check each sublist present in the new_list for sublist in duplicate_list: for other in new_list: # Checking of presence of sublist present in other sublist is done if sublist != other and set(sublist).issubset(other): #issubset is used to check presence of one sublist in another sublist # Remove all the repeating sublist new_list.remove(sublist) break #break is used to stop the loop so that it does not keep checking continuosly print(new_list)
Output
The output of the above code is as follows:
[[Aayush, Shyam, John], [Henry, Joe], [David, Stefen, Damon]]
This method is more suitable when the list is too long and contains a large number of sublists with many elements.
Set operation
In this operation, sublists existing in other sublists are deleted with the help of set operation. In this approach we can convert each sublist in the list into a set and with the help of different operations we can remove all sublists present in other sublists. We can understand it more clearly through the following example:
Example
duplicate_list = [[Aayush, Shyam, John], [Shyam, John], [Henry, Joe], [David, Stefen, Damon], [David, Stefen]] new_list = [] for sublist in duplicate_list: is_subset = False for other in duplicate_list: if sublist != other and set(sublist).difference(set(other)) == set(): #The difference operation is used to calculate the difference betwen two sets is_subset = True #When the sublist is present in another sublist the result of is_subset will be true break #Once the result is found to be true, the loop is broke and all the other sublist are copied into the new_list if not is_subset: new_list.append(sublist) print(new_list)
Output
The output of the above code is as follows:
[[Aayush, Shyam, John], [Henry, Joe], [David, Stefen, Damon]]
All sublists present in other sublists have been deleted.
in conclusion
The problem of deleting a sublist that already exists in another sublist is a problem that users often face, and many times it will consume a lot of users' time. Therefore, it is possible to quickly delete all sublists that exist within another sublist using different methods suggested in the previous article.
The above is the detailed content of Python - Remove sublist that exists within another sublist. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

The article discusses the role of virtual environments in Python, focusing on managing project dependencies and avoiding conflicts. It details their creation, activation, and benefits in improving project management and reducing dependency issues.
