Assign value to unique number in list in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

# 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]
raja
Published on 09-Sep-2020 12:15:35
Advertisements