-4

quiz question :

a=[1,2,3,4,5,6,7,8,9,10]

result for :

print a([-1:-5])

I don't know the actual output for this operation please update.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 2
    These type of questions are not well received in SO. – Ch3steR Feb 18 '20 at 07:19
  • 1
    It is faster to run it than to ask for answers – Babak Bandpey Feb 18 '20 at 07:23
  • Above print statement will throw an error. Syntax is not correct. Please check the question again. – Prashant Kumar Feb 18 '20 at 07:25
  • @PrashantKumar It wouldn't throw an error. Please refer to docs. – Ch3steR Feb 18 '20 at 07:30
  • @Ch3steR see this : `Python 3.6.8 (default, Apr 9 2019, 04:59:38) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a=[1,2,3,4,5,6,7,8,9,10] >>> print a([-1:-5]) File "", line 1 print a([-1:-5]) ^ SyntaxError: invalid syntax` – Prashant Kumar Feb 18 '20 at 07:32
  • @PrashantKumar That's because OP wrote `a([-1:-5])` whereas it should be written as `a[-1:-5]` and `a[-1:-5]` is valid. – Ch3steR Feb 18 '20 at 07:35
  • I think what he wanted is a[-5:], which then gives [6, 7, 8, 9, 10]. Who knows.. – kalzso Feb 18 '20 at 07:36
  • @Ch3steR I don't want to guess what he has written. I can fix it if I want to, by guessing everything. We should not guess here instead ask user to correct question by pointing out the problem in question. – Prashant Kumar Feb 18 '20 at 07:37
  • Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – kalzso Feb 18 '20 at 07:37
  • The syntax error comes from the missing parentheses in the call to `print`. – Matthias Feb 18 '20 at 07:51
  • Does this answer your question? https://stackoverflow.com/questions/13672627/why-does-my-negative-slicing-in-python-not-work – Ch3steR Feb 18 '20 at 08:47

1 Answers1

1

To start with, it's invalid syntax.

But even if you had your syntax correct, it's going to give you an empty array. Because it is not going to slice between -1 to -5, but it will slice between -5 to -1. Imagine that slicing will only work from a smaller number: larger number.

so

print(a[-1:-5])

will result in

[]

Whereas

print(a[-5:-1])

will result in the elements 5th position from the end of the list to the first position from the end of the list which is

[6, 7, 8, 9]
  • `a[-1:-5:-1]` will work. *Imagine that slicing will only work from a smaller number: larger number.* This doesn't make sense. – Ch3steR Feb 18 '20 at 07:37