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
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
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
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:
1
...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
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)