Joseph Medhat Joseph Medhat - 4 years ago 105
Python Question

Confused with Python range and list indexes

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?


Answer Source
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 second 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 at'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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download