Terry Li
Terry Li

Reputation: 17268

Someone help me understand the square bracket in the following Python code?

import xlrd
book = xlrd.open_workbook("univ_list.xls")
sh = book.sheet_by_index(0)
for r in range(sh.nrows)[1:]: # line 4
    print sh.row(r)[:4] # line 5

What does [1:] mean in line 4? What does [:4] mean in line 5?

Upvotes: 1

Views: 156

Answers (2)

maneesha
maneesha

Reputation: 695

[1:] means you just want to get the items from position 1 on in your list, string, etc.

[:4] means you want to get up to item 4 in your string or list.

Remember, numbering starts at 0.

so in f = 'apple', f[0]='a', f[1]='p', f[1:]='pple'

Read up on slice notation -- there's a lot more you can do with that.

Upvotes: 0

Ry-
Ry-

Reputation: 225281

Here's an example of what you're seeing on Wikipedia: http://en.wikipedia.org/wiki/Array_slicing#1991:_Python

It's called array slicing. [1:] gets all the items except for the first, and [:4] gets the first 4 items.

Upvotes: 5

Related Questions