Python colon not a sequence of numbers?

Question:

In r code, the sequence of integers from 1 to 4:

1:4

How can I replicate this in python 3? The use case is selecting from a pandas dataframe using iloc:

df.iloc[1:4]
Asked By: DDDD

||

Answers:

In Python, in order to generate a range of numbers use the function range.

range(1, 5)

This will generate numbers from 1 to 4. If you are in Python 2, range will give you a list, and if you are in Python 3, it will give you a range object.

If you are in Python 3, and you want a list, just use the list function to convert your range to a list

>>> list(range(1, 5)
[1, 2, 3, 4]
Answered By: lmiguelvargasf

Use range(1, 5) for giving you that set of integers from 1 to 4 (inclusive of both)

Answered By: Matthew Gaiser

You can use

mylist=list(range(1,5))
print(mylist)

list() converts given range object into list

Answered By: Hetal Thaker

To generate a range of number from 1 to 4 (inclusive), use: range(1, 5) or range(1, 4+1)

Just a few things to note:

  • The code range(x, y) generates a range from (and including) x up to (but not including) y. If you want to include y, add 1 to it (as I did above).

  • range(x, y) works a bit differently in Python 2 vs. Python 3. I won’t go into the details here, but I recommend using Python 3 (which hopefully you’re already using).

  • range(x) is will generate a range from (and including) zero up to (but not including) x. So range(x) is basically the same as range(0, x).

  • The range function will generate a range object; that is, it doesn’t actually create a list of all the integers between x and y. If you do want a list of integers between x and y, use this code:

    some_list = list(range(x, y))
    

However, if you’re looking to pull out a slice of values out of a sequential container, this might work:

from itertools import islice
values = islice(df.iloc, 1, 5)  # returns an iterator
values = list(values)  # extracts the values from the iterator into a list
Answered By: J-L

Python’s slicing syntax doesn’t produce a range of integers; it produces one or more slice objects which are passed to the __getitem__ method of the appropriate type. That is,

df.iloc[1:4]

is equivalent to either

def.iloc[slice(1,4)]

or

df.iloc.__getitem__(slice(1,4))
Answered By: chepner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.