Python | Assign value to unique number in list
We can assign all the numbers in a list a unique value that upon repetition it retains that value retained to it. This is a very common problem that is faced in web development when playing with id’s. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using
enumerate() + list comprehension
List comprehension can be used to perform this particular task along with the enumerate function which selects the unique numbers with the help of set and former helping in the iteration in the list.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
The original list is : [1, 4, 6, 1, 4, 5, 6] The unique value list is : [0, 1, 3, 0, 1, 2, 3]
Method #2 : Using
setdefault() + map() + count()
The combination of all the three function can also be used to perform this particular task. Map binds all the like elements, setdefault assigns them unique number and count function helps map to find number of total occurrences.
The original list is : [1, 4, 6, 1, 4, 5, 6] The unique value list is : [0, 1, 2, 0, 1, 5, 2]