I would like to remove the numbers from the list of three in three positions and then store them in a new list. I thought of doing something like n 3 but don´t know how to implement it.
[1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 1, 6, 1, 4, 7, 2, 4, 8, 4, 6, 9, 6, 5]
This is my list and I would like to create a new list like this:
[1,2,3,4,5,6,7,8,9]
Thank you in advance
CodePudding user response:
As far as I understand, you want to pick one element in every three elements. For that, you can use slicing [::3]
, where 3
means the step size:
lst = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 1, 6, 1, 4, 7, 2, 4, 8, 4, 6, 9, 6, 5]
output = lst[::3]
print(output) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
CodePudding user response:
Using set removes all multiples and also changes the type so then we convert it back to a list. Learn more about set here: https://docs.python.org/3/tutorial/datastructures.html#sets
my_list=[1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 1, 6, 1, 4, 7, 2, 4, 8, 4, 6, 9, 6, 5]
new_list=list(set(my_list))
CodePudding user response:
It is obvious that your question needs improvement, however, if i understood correctly, you want to remove redundancy in which case a much much simpler solution is to convert your list to a set and it'll be taken care of like so:
unique = set(some_list)
Do note that unique's api will be that of a set but if you specifically need a list you can do this:
unique = list(set(some_list))
Happy coding-