OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

getting the last element with slice() object

  • Thread starter Thread starter anverx
  • Start date Start date
A

anverx

Guest
How do i create a slice() object so that it would include the last element of a list/string

Code:
s = 'abcdef'
s[slice(2,4)]

works fine.
Say I wanted to get elements from second to the end, the equivalent of s[2:]

Code:
s[slice(2)]      # only gives first two elements, argument is interpreted as the end of the range
s[slice(2,)]     # same as above
s[slice(2, -1)]  # gives a range from second to the end excluding the last element
s[slice(2, 0)]   # gives empty as expected,  since end of range before the start

I can get specifically the last element with slice(-1, -2, -1), this won't work correctly for more then one element.
<p>How do i create a slice() object so that it would include the last element of a list/string</p>

<pre class="lang-py prettyprint-override"><code>s = 'abcdef'
s[slice(2,4)]
</code></pre>

<p>works fine.<br>
Say I wanted to get elements from second to the end, the equivalent of <code>s[2:]</code></p>

<pre><code>s[slice(2)] # only gives first two elements, argument is interpreted as the end of the range
s[slice(2,)] # same as above
s[slice(2, -1)] # gives a range from second to the end excluding the last element
s[slice(2, 0)] # gives empty as expected, since end of range before the start
</code></pre>

<p>I can get specifically the last element with <code>slice(-1, -2, -1)</code>, this won't work correctly for more then one element.</p>
 

Latest posts

Top