Reputation: 31
I'm still beginner in python world and one of the things that made my head turns.. is the range
built-in and the list indexes.
How can I know if the range would or wouldn't take the last number?
For example
range(15)
will it count to 15 or 14?range(1,15)
will it count to 15 or 14?List_1 [ :15]
will it count to 16 (last element) or rest at 15(element before it) list_1[1: ]
supposing that the list is 16 item will it count to the last element ?List_1[1:15]
will it count to last element or the one before it? Upvotes: 0
Views: 954
Reputation: 2782
for i in range(15):
print i #will print out 0..14
for i in range(1, 15):
print i # will print out 1..14
for i in range (a, b, s):
print i # will print a..b-1 counting by s. interestingly if while counting by the step 's' you exceed b, it will stop at the last 'reachable' number, example
for i in range(1, 10, 3):
print i
> 1
> 4
> 7
List Splicing:
a = "hello" # there are 5 characters, so the characters are accessible on indexes 0..4
a[1] = 'e'
a[1:2] = 'e' # because the number after the colon is not reached.
a[x:y] = all characters starting from the character AT index 'x' and ending at the character which is before 'y'
a[x:] = all characters starting from x and to the end of the string
In the future, if you ever wonder what the behavior of python is like, you can try it out in the python shell. just type python in the terminal and you can enter any lines you want (though this is mostly convenient for one-liners rather than scripts).
Upvotes: 2
Reputation: 901
Well, here is a much prose version of previous answers
range(15)
actually generates a list with indexes from 0 through 14range(0, 15)
does the same; except that both starting and ending indexes are specifiedlist[:14]
accesses contents of list
including 14th index (15th element)list[1:]
access contents of list
from 1st index (2nd element) until (and including) the last elementUpvotes: 0
Reputation: 6641
The best way to clarify such doubts is to play with the REPL:
>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = list(range(10))
>>> x[:3]
[0, 1, 2]
>>> x[:1]
[0]
>>> x[1:10]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 0