kiri
kiri

Reputation: 2642

Python range of a list?

I'd like to be able to get a range fields of a list.

Consider this:

list = ['this', 'that', 'more']

print(list[0-1])

where the [0-1] should return the first and second fields.

Upvotes: 1

Views: 382

Answers (2)

user2555451
user2555451

Reputation:

You will want to use Python's slice notation for this:

>>> lst = ['this', 'that', 'more']
>>> print(lst[:2])
['this', 'that']
>>>

The format for slice notation is [start:stop:step].

Also, I changed the name of the list to lst. It is considered a bad practice to name a variable list since doing so overshadows the built-in.

Upvotes: 5

RMcG
RMcG

Reputation: 1095

use:

list = ['this', 'that', 'more']
print(list[0:2])

Upvotes: 3

Related Questions