Joseph Medhat
Joseph Medhat

Reputation: 31

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

Upvotes: 0

Views: 954

Answers (3)

Jeremy Fisher
Jeremy Fisher

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

aliasm2k
aliasm2k

Reputation: 901

Well, here is a much prose version of previous answers

  1. range(15) actually generates a list with indexes from 0 through 14
  2. range(0, 15) does the same; except that both starting and ending indexes are specified
  3. list[:14] accesses contents of list including 14th index (15th element)
  4. list[1:] access contents of list from 1st index (2nd element) until (and including) the last element

Upvotes: 0

Caridorc
Caridorc

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

Related Questions