
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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
- How to Assign a Serial Number to Duplicate or Unique Values in Excel?
- Python Program to assign each list element value equal to its magnitude order
- Program to find the number of unique integers in a sorted list in Python
- Largest Unique Number in Python
- Count unique sublists within list in Python
- Program to find number of unique people from list of contact mail ids in Python
- Unique Number of Occurrences in Python
- 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
- List assign() function in C++ STL
