create a map and take unique values in python

To create a map in Python, you can use the built-in map() function. This function takes two arguments - a function and an iterable. It applies the function to each element of the iterable and returns a new iterable with the results.

Here's an example of how to create a map that squares each element of a list:

main.py
my_list = [1, 2, 3, 4, 5]
squared_list = map(lambda x: x**2, my_list)
print(list(squared_list))  # Output: [1, 4, 9, 16, 25]
125 chars
4 lines

To take unique values in Python, you can use a set. A set is an unordered collection of unique elements. You can convert a list (or any iterable) to a set to remove duplicates:

main.py
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
unique_set = set(my_list)
print(list(unique_set))  # Output: [1, 2, 3, 4, 5]
133 chars
4 lines

Alternatively, you can use a list comprehension to get unique values:

main.py
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
unique_list = [x for i, x in enumerate(my_list) if x not in my_list[:i]]
print(unique_list)  # Output: [1, 2, 3, 4, 5]
175 chars
4 lines

related categories

gistlibby LogSnag