2

I wanna scroll sys.argv from the second to the penultimate argument. why it doesn't work?

for arg in sys.argv[1: :len(sys.argv)-1] :
    print arg  
Seba92
  • 446
  • 1
  • 4
  • 17
  • 3
    You put a `:` too much: `sys.argv[1:len(sys.argv)-1]`. Also, you can use negative indexes: `sys.argv[1:-1]`. – Bakuriu May 30 '14 at 17:22

3 Answers3

6

You have a mistake in your code: you shouldn't put two colons, but just one. Here's how it works:

  • In order to exclude n first elements, the syntax is [n:].

  • In order to exclude n last elements, you don't need to count the number of elements in an array. Instead, you use: [:-n] syntax.

  • If you want to exclude first x elements and last y elements, you can combine both: [x:y].

In your case, to get the array without the first and the last arguments, you may simply do:

sys.argv[1:-1]

Like this:

for arg in sys.argv[1:-1]:
    print arg
Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
  • @ZeroPiraeus: I thought it's clear enough, since I provided the correct syntax **and** explained how the syntax works. Since it appears that it's not, I edited my answer to include the actual mistake in OP's code. – Arseni Mourzenko May 30 '14 at 17:51
  • 1
    Thanks for that ... since OP wants to know "why it doesn't work?", I think it's important to tell them ... anyway, downvote replaced with upvote :-) – Zero Piraeus May 30 '14 at 17:54
  • I thought this explanation was an excellent example of slowly building up the syntax in steps and then (and only then) giving the actual code fix. – schodge May 30 '14 at 20:58
2

Your problem is that you have too many colons, resulting in an extended slice.

Because of the extra colon in [1::len(sys.argv)-1] (the space between the colons in your version is unnecessary, and may be what confused you), you're saying:

  • Give me all the elements from index 1 ...
  • ...to the end (because there's nothing between the first and second colons) ...
  • with a stride of len(sys.argv)-1.

Obviously, if you start at the 2nd element of a sequence and then stride forward by len(sequence) - 1, you get to the end, and there's nothing left.

If you drop the extra colon, your code will work ...

for arg in sys.argv[1:len(sys.argv)-1]:
    print arg  

... but Python allows you to use negative indexes to count from the end of the sequence you're slicing, so you can replace the whole thing with:

for arg in sys.argv[1:-1]:
    print arg  
Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
0

sys.argv is a list, so you can apply slicing in order to get only a certain part of the list, for example if you only want to iterate from element two to the penultimate. Generally, if lst is a list

lst[0]

is the first element of the list, and

lst[-1]

is the last. Example:

>>> x = [1,2,3,4,5,6]
>>> x[1:-1]
[2, 3, 4, 5]

With slicing, your for loop should look like

for arg in sys.argv[1:-1]:
    print(arg)
timgeb
  • 76,762
  • 20
  • 123
  • 145