A couple of minor points regarding tuples. When you take a slice of a tuple, there are 3 parameters:
– the start index
– the end index
– the step
aTuple = (1, 2, 3, 4, 5) print (aTuple[1:3]) print (aTuple[0:7]) print(aTuple[3:1:-1])
which produces:
(2, 3) (1, 2, 3, 4, 5) (4, 3)
It doesn’t matter that, in the second instance, the end index is beyond the last index of the string. Also, the end index is excluded.
If you want to go to the start of the tuple, then you need to set the end index to -1:
print(aTuple[3:-1:-1])
But this doesn’t produce the expected result.
( )
This is because negative indexes are from the end of the tuple. So -1 is the last element in the tuple.
print(aTuple[2:-1])
produces:
(3, 4)
Again, this excludes the final index. To include either the start or the end of the tuple as the final element of the result, the end index should be left empty:
print(aTuple[2:]) print(aTuple[2::-1])
giving:
(3, 4, 5) (3, 2, 1)
Finally, in most cases where you can use a tuple, you can use a list instead:
aList = list(aTuple) print (aList[1:3]) print (aList[0:7]) print(aList[3:1:-1]) print(aList[3:-1:-1]) print(aList[2:-1]) print(aList[2:]) print(aList[2::-1])
producing similar results as before, but lists instead of tuples:
[2, 3] [1, 2, 3, 4, 5] [4, 3] [] [3, 4] [3, 4, 5] [3, 2, 1]
But this doesn’t work for the % operator:
print("aTuple[0]=%s, aTuple[1]=%s, aTuple[2]=%s, aTuple[3]=%s, aTuple[4]=%s" % aTuple)
print("aList[0]=%s, aList[1]=%s, aList[2]=%s, aList[3]=%s, aList[4]=%s" % aList)
aTuple[0]=1, aTuple[1]=2, aTuple[2]=3, aTuple[3]=4, aTuple[4]=5
Traceback (most recent call last):
File "c:/prr/cgibin/data/prr/codebright/tuple.py", line 29, in <module>
print("aList[0]=%s, aList[1]=%s, aList[2]=%s, aList[3]=%s, aList[4]=%s" % aList)
TypeError: not enough arguments for format string