Take numbers from a list in a specific order in Python

Question:

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

Asked By: toctoc

||

Answers:

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))
Answered By: Flow

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]
Answered By: j1-lee

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-

Answered By: siphr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.