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 | Check if list contains all unique elements
- Python | Count unique sublists within list
- Python Program for Product of unique prime factors of a number
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Pandas dataframe.assign()
- How to assign values to variables in Python and other languages
- Python Number | cmp(list) method
- Generating random number list in Python
- Python | Number of values greater than K in list
- Python | Find closest number to k in given list
- Python | Largest number possible from list of given numbers
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.