1

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.

daniula
  • 6,898
  • 4
  • 32
  • 49
user3079411
  • 35
  • 1
  • 5
  • Is the fact that the element is a single digit the only condition you have? – Lix Dec 08 '13 at 19:09
  • @AshwiniChaudhary - all of the information was in the original version. The text speaking about "a single digit" was referring to the possible regex that would match `1,2,3` - but not the condition of "every third element". – Lix Dec 08 '13 at 19:18
  • @Lix I just removed the `regex` tag, I am not sure what are you referring to. All the [other changes](http://stackoverflow.com/posts/20457638/revisions) were made by OP himself. – Ashwini Chaudhary Dec 08 '13 at 19:20
  • @AshwiniChaudhary - I'm talking about your (now deleted) comment. The OP's edit didn't render your answer invalid - it didn't change the underlying question. – Lix Dec 08 '13 at 19:22

5 Answers5

9

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.

Community
  • 1
  • 1
hwnd
  • 69,796
  • 4
  • 95
  • 132
0

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

karthik27
  • 484
  • 1
  • 4
  • 12
  • This is not what the OP is asking for. The question states that the output should be every third element starting from (and including) the first element. `"starting from the first number, and every third number"` – Lix Dec 08 '13 at 19:26
0
lst = [1, 10, 100, 2, 20, 200, 3, 30, 300]

print [lst[i] for i in xrange(0, len(lst), 3)]
smac89
  • 39,374
  • 15
  • 132
  • 179
-1
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]]
yemu
  • 26,249
  • 10
  • 32
  • 29
-1

Simple list comprehension:

[x for x in lst if x < 10 and x >= 0]
mchfrnc
  • 5,243
  • 5
  • 19
  • 37