2

Sorry if this has already been asked, I couldn't find it anywhere. Basically how do I get 2 separate ranges within a list in Python.

If I want the 1st, 2nd, 5th and 6th elements of a list I know I can do this,

l = range(0,15)
l[1:3]+l[5:7]

but this assumes that l is easy to write. However I am scrapping something from a webpage using BeautifulSoup4, so I'm using soup.find_all (which gives me a list), so I can't simply write out 2 lists, l and concatenate them.

I want an answer that is something like

l = range(0,15)
l[1:3,5:7]

(but of course without the error) :)

1
  • 4
    what is wrong with l[1:3]+l[5:7]? Commented Apr 21, 2015 at 20:23

4 Answers 4

3

This might be what you want. itemgetter creates a function that retrieves the listed indices:

>>> import operator
>>> snip = operator.itemgetter(1,2,5,6)
>>> snip(range(15))
(1, 2, 5, 6)
>>> snip('abcdefg')
('b', 'c', 'f', 'g')
>>> snip([1,2,3,4,5,6,7,8])
(2, 3, 6, 7)
Sign up to request clarification or add additional context in comments.

Comments

2

I would do this with a function:

def multi_range(l, *args):
    output = []
    for indices in args:
        output += l[indices[0]:indices[1]]
    return output

So the first argument would be the list, and the rest of the parameters are tuples with the indices you're looking to pull. It would work fine with a long list name:

long_list_name = range(0, 15)
print multi_range(long_list_name, (1, 3), (5, 7))
>>> [1, 2, 5, 6]

Comments

1
l = range(0, 15)
print([l[i] for i in [1,2, 5,6]])

Not sure why you think l[1:3]+l[5:7] is hard, find_all returns a normal python list like any other.

Or using map:

l = range(0, 15)
print(list(map(l.__getitem__,(1,2,5,6))))

Comments

-1

Is this OK?

indices = [1, 2, 5, 6]
selected = [l[i] for i in indices]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.