0

I'm using python slicing to take elements from a list but don't know if there are going to be enough in there.

At the moment I'm doing this, which feels ugly:

        if index + num_to_take > len(values):
            bit = values[index: ]
        else:
            bit = values[index:index + num_to_take]

Is there a better way?

The Gribble
  • 99
  • 1
  • 6
  • 1
    Just use `bit = values[index:index + num_to_take]` by itself. It will default to `values[index: ]` if there aren't enough numbers. – John Coleman Jun 02 '20 at 14:18

2 Answers2

1

You can skip the if condition altogether.

bit = values[index:index + num_to_take] would run just fine.

Taking advantage of how slicing works in python. Read this for more information.

paradocslover
  • 2,932
  • 3
  • 18
  • 44
1

There is no need of ifs

bit = values[index:index + num_to_take] will run fine

Rajas Rasam
  • 175
  • 2
  • 3
  • 9