

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Assign value to unique number in list in Python
Many times we need to identify the elements in a list uniquely. For that we need to assign unique IDs to each element in the list. This can be achieved by the following two approaches using different inbuilt functions available in Python.
With enumerate and set
The enumerate function assigns unique ids to each element. But if the list already as duplicate elements then we need to create a dictionary of key value pairs form the list and assign unique values using the set function.
Example
# Given List Alist = [5,3,3,12] print("The given list : ",Alist) # Assigning ids to values enum_dict = {v: k for k, v in enumerate(set(Alist))} list_ids = [enum_dict[n] for n in Alist] # Print ids of the dictionary print("The list of unique ids is: ",list_ids)
Output
Running the above code gives us the following result −
The given list : [5, 3, 3, 12] The list of unique ids is: [2, 0, 0, 1]
With count() and map()
The map() function applies the same function again and again to the different parameters passed to it. But the count method returns the number of elements with the specified value. So we combine these two get the list of unique IDs for the elements of a given list in the below program.
Example
from itertools import count # Given List Alist = [5,3,3,12] print("The given list : ",Alist) # Assign unique value to list elements dict_ids = list(map({}.setdefault, Alist, count())) # The result print("The list of unique ids is: ",dict_ids)
Output
Running the above code gives us the following result −
The given list : [5, 3, 3, 12] The list of unique ids is: [0, 1, 1, 3]
- Related Questions & Answers
- Assign ids to each unique value in a Python list
- Python - Unique keys count for Value in Tuple List
- Python program to unique keys count for Value in Tuple List
- Assign range of elements to List in Python
- Python Program to assign each list element value equal to its magnitude order
- Largest Unique Number in Python
- Program to find the number of unique integers in a sorted list in Python
- Unique Number of Occurrences in Python
- Count unique sublists within list in Python
- List assign() function in C++ STL
- Assign multiple variables with a Python list values
- How do I assign a dictionary value to a variable in Python?
- How do we assign a value to several variables simultaneously in Python?
- Python - Assign a specific value to Non Max-Min elements in Tuple
- Program to find number of unique people from list of contact mail ids in Python