Table of Contents
Arrays in Python
Input and output scenarios
Use For Loop
Example
Output
Use Collection
Use Enumerate() function
grammar
Use Dict.fromkeys()
parameter
Home Backend Development Python Tutorial Python program to remove duplicate elements from array

Python program to remove duplicate elements from array

Sep 07, 2023 am 11:13 AM
python array delete

Python program to remove duplicate elements from array

An array is a collection of elements of the same data type. Each element in the array is identified by an index value. It is one of the simplest data structures in which each data element can be accessed directly using only its index number.

Arrays in Python

Python has no specific data structure to represent arrays. Here we can use List an array.

 [6, 4, 1, 5, 9]
  0  1  2  3  4
Copy after login

Indices in Python start from 0. In the above code block, the integers 6,4,1,5,9 are array elements and 0,1,2,3,4 are their respective index values.

Arrays can have duplicate elements. In this article, we will discuss several ways to remove duplicate elements from an array.

Input and output scenarios

Suppose we have an input array containing duplicate values. And the resulting array will contain only unique elements.

Input array:
A = [1, 5, 3, 6, 3, 5, 6, 1]
Output array:
[1, 5, 3, 6]
Copy after login

Elements 1, 5, 3, 6 are the only elements in the given array.

Use For Loop

We will use a for loop to iterate over all the array elements and in each iteration we will use the not in operator to find duplicates.

Example

In this example, first we initialize an empty list result to store all the unique values ​​found in the for loop.

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = []

for i in lst: 
   if i not in result: 
      result.append(i) 

print ("The array after removing repeated elements: ", result)
Copy after login

Output

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]
Copy after login
Copy after login
Copy after login

The "not in" operator is checking whether the current element exists in an empty list. If it does not exist, the element is appended to the result list, otherwise it is ignored.

Use Collection

Set is a data structure in Python that stores unique data. This means, it does not allow storing duplicate elements.

Example

In this example, we will simply convert the array from a list data type to a collection data type.

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = list(set(lst)) 

print ("The array after removing repeated elements: ", result) 
Copy after login

Output

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 3, 5, 6]
Copy after login

As we all know, duplicates cannot be accommodated in a collection data structure, so we get an output array containing all unique elements.

Use Enumerate() function

Enumerate() is a Python built-in function that accepts an iterable object and returns a tuple containing the count and values ​​obtained by iterating the iterable object.

grammar

enumerate(iterable, start=0)
Copy after login

Example

We will implement the enumerate() function in the list comprehension to keep track of the index of each element in the array, and then we can use the index value i to check whether element n is already present in the array up to index i. If it exists, we ignore the element, otherwise we add it to the resulting array.

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = [i for i, n in enumerate(lst) if n not in lst[:i]]

print ("The array after removing repeated elements: ", result) 
Copy after login

Output

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]
Copy after login
Copy after login
Copy after login

Use Dict.fromkeys()

python dict.fromkeys() method is used to create a dictionary based on the given set of keys and values. Dictionaries store a unique set of keys.

grammar

dict.fromkeys(keys, values)
Copy after login

parameter

  • Keys - This is a required parameter. It takes an iteration to specify the keys of the new dictionary.

  • Values - It is an optional parameter, the values ​​of all keys. The default value is "None".

Example

In this example, we will create a dictionary containing only keys, not key and value pairs.

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array
 
result = list(dict.fromkeys(lst))

print ("The array after removing repeated elements: ", result) 
Copy after login

Output

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]
Copy after login
Copy after login
Copy after login

As we all know, the keys in the dictionary cannot be repeated. Therefore, the fromkeys() method removes duplicate values ​​on its own. Then we convert it to a list to get an array containing all unique elements.

These are some of the methods by which we can remove duplicate elements from an array.

The above is the detailed content of Python program to remove duplicate elements from array. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1245
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles