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.
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]
- Python | Assign ids to each unique value in a list
- Python | Assign range of elements to List
- Python | Assign multiple variables with list values
- Python | Get unique values from a list
- Python | Unique pairs in list
- Python | Get unique tuples from list
- Python | Unique dictionary filter in list
- Python | Get Unique values from list of dictionary
- Python | Count unique sublists within list
- Python | Check if list contains all unique elements
- Python - Get a sorted list of random integers with unique elements
- Python | Extract unique tuples from list, Order Irrespective
- Python | Find the number of unique subsets with given sum in array
- Python Program for Product of unique prime factors of a number
- Python | Pandas dataframe.assign()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.