For example if I have a list like the following
lst = [1, 10, 100, 2, 20, 200, 3, 30, 300];
How could I get back [1, 2, 3]
? Basically it would be starting from the first number, and every third number.
For example if I have a list like the following
lst = [1, 10, 100, 2, 20, 200, 3, 30, 300];
How could I get back [1, 2, 3]
? Basically it would be starting from the first number, and every third number.
The step argument using slice notation.
>>> lst[::3]
[1, 2, 3]
Update:
Take a look at this post: Python's slice notation
, it will explain further in detail.
if don;t exactly understand your question , you could use the built in sorted function to sort it and then get the first 3 elements
s = sorted(lst)[:3]
if you want 1 or 2 or 3 or whatever its there in the list
[x for x in lst if x in range(1,4)]
Hope this helps
lst = [1, 10, 100, 2, 20, 200, 3, 30, 300]
print [lst[i] for i in xrange(0, len(lst), 3)]
for item in lst:
if item in [1,2,3]:
new_lst.append(item)
or shorter using list comprehension:
new_lst=[item for item in lst if item in [1,2,3]]