2 Replies - 2874 Views - Last Post: 28 July 2010 - 05:22 AM Rate Topic: -----

#1 Cuzzie   User is offline

  • D.I.C Regular
  • member icon

Reputation: 72
  • View blog
  • Posts: 342
  • Joined: 16-July 10

Subscripting in Python

Posted 28 July 2010 - 04:54 AM

Okay, so I saw a person post this code as solution to extracting even and odd numbers from a list of range(1,10).

>>> x = range(1,10)
>>> print x
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[::2]
[1, 3, 5, 7, 9]
>>> x[1::2]
[2, 4, 6, 8]



I tried it, and it really works. Tried doing some googling, can't find much information on this... '::' thing. Can anyone explain to me what it does please? Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Subscripting in Python

#2 moopet   User is offline

  • binary decision maker
  • member icon

Reputation: 345
  • View blog
  • Posts: 1,190
  • Joined: 02-April 09

Re: Subscripting in Python

Posted 28 July 2010 - 05:08 AM

[x:y:z] as a suffix to a list denotes a range, where x is the start index, y is the end index and z is the stepping.
It's semantically similar to for i = x to y step z in BASIC, for instance.
You can leave values out, so [:10] means the range is 0-10, [::3] means it's every third entry and so forth. You can also use negative indices: [3:-10:5] means start at 3, increment by 5, finish at the tenth from the end of the list.
Was This Post Helpful? 2
  • +
  • -

#3 Cuzzie   User is offline

  • D.I.C Regular
  • member icon

Reputation: 72
  • View blog
  • Posts: 342
  • Joined: 16-July 10

Re: Subscripting in Python

Posted 28 July 2010 - 05:22 AM

Ohh!! I understand it now! Thanks a lot Moopet!! :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1