search
HomeBackend DevelopmentPython TutorialPython program to find distinct elements from two arrays

Python program to find distinct elements from two arrays

In programming, an array is a data structure used to store a collection of homogeneous data elements. Each element in the array is identified by a key or index value.

Arrays in Python

Python has no specific data type to represent arrays. Instead, we can use List as an array.

[1, 4, 6, 5, 3]

Finding distinct elements from two arrays means identifying unique elements between two given arrays.

Input and output scenarios

Suppose we have two arrays A and B with integer values. And the resulting array will have different elements than the two arrays.

Input arrays:
A = [1, 2, 3, 4, 5]
B = [5, 2, 6, 3, 9]
Output array:
[1, 6, 4, 9]

Elements 1, 6, 4, and 9 are unique values ​​between the two arrays.

Input arrays:
A = [1, 2, 3, 4, 5]
b = [3, 4, 5, 1, 2]
Output array:
[]

No distinct elements found in the given 2 arrays.

Use for loop

We will use a for loop for arrays with equal number of elements.

Example

In the following example, we will define a for loop using the list comprehension method.

arr1 = [1, 2, 3, 4, 5]
arr2 = [5, 2, 6, 3, 9]

result = []
for i in range(len(arr1)):
   if arr1[i] not in arr2:
      result.append(arr1[i])
   if  arr2[i] not in arr1:
      result.append(arr2[i])
        
print("The distinct elements are:", result)

Output

The distinct elements are: [1, 6, 4, 9]

Here we find different elements by using for loop and if condition. Initially, the loop is iterated and verified if the element arr1[i] is not present in the array arr2, then if the element is a different element we append that element to the result variable. In the same way, we validate the second array element to the first array. and store the different elements in the resulting array.

Example

Let's use another set of arrays and find different elements.

a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 1, 2]

result = []
for i in range(len(a)):
   if a[i] not in b:
      result.append(a[i])
   if  b[i] not in a:
      result.append(b[i])
        
print("The distinct elements are:", result)

Output

The distinct elements are: []

No distinct elements found in the given array set.

Use Collection

Finding different elements in two arrays is very similar to finding the symmetric difference between two sets. By using the Python Sets data structure and its properties, we can easily identify the different elements in two arrays.

Example

First, we convert the list to a set and then apply the symmetric difference property ^ between the two sets to get the distinct elements.

a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7, 8]
result = list((set(a) ^ set(b)))
if result:
    print("The distinct elements are:", result)
else:
    print("No distinct elements present in two arrays")

Output

The distinct elements are: [1, 2, 6, 7, 8]

We can also use the set.symmetry_difference() method to find different elements in two arrays. The symmetry_difference() method returns all unique items present in the given collection.

grammar

set_A.symmetric_difference(set_B)

Example

Let's see an example of getting different elements from two arrays.

a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7, 8]

result = list(set(a).symmetric_difference(set(b)))

if result:
    print("The distinct elements are:", result)
else:
    print("No distinct elements present in two arrays")

Output

The distinct elements are: [1, 2, 6, 7, 8]

Here we use the symmetry_difference() method to get the symmetry difference of A and B to the result variable. Then use the list() function to convert the set of unique elements into a list again.

Example

If no different elements are found, the symmetry_difference() method will return an empty set.

a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 1, 2]

result = list(set(a).symmetric_difference(set(b)))

if result:
    print("The distinct elements are:", result)
else:
    print("No distinct elements present in two arrays")

Output

No distinct elements present in two arrays

In the above example, all elements are public elements. In this way, the symmetry_difference() method returns the empty set.

The above is the detailed content of Python program to find distinct elements from two arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

What is the difference between arrays and lists in Python?What is the difference between arrays and lists in Python?May 05, 2025 am 12:06 AM

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

What module is commonly used to create arrays in Python?What module is commonly used to create arrays in Python?May 05, 2025 am 12:02 AM

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft