0
Av = [32,5,3,1,3,4,5]
A = Av[0:int(len(Av)/2)]
B = Av[int(len(Av)/2):-1]
print(A,B)

When I run this block of code, I get

[32, 5, 3] [1, 3, 4]

The last value of Av is 5. But it is not showing up on the list B..

n1tr0z3n
  • 53
  • 2
  • 9

3 Answers3

2

In python when you use index slicing Av[a:b] you get the elements from position a (included) to position b (excluded). Because -1 refers to the last position, if you do Av[a:-1], the last element won't be included.

If you want to include the last element, just omit the final index -1, that is use Av[a:]. Your code should be like this:

Av = [32,5,3,1,3,4,5]
A = Av[0:int(len(Av)/2)]
B = Av[int(len(Av)/2):]
print(A,B)

Take a look at https://stackoverflow.com/a/509295/7558835 answer. It explains very clearly how does index slicing work.

Diego Palacios
  • 1,096
  • 6
  • 22
2

When you use the slice [x:-1], it doesn't include the value at index -1 (last position), because it is non-inclusive.

Instead, use [x:], which will give a slice that includes x and all values to its right:

B = Av[int(len(Av)/2):]

Output:

>>>B
>>>[1, 3, 4, 5]
Paul Lemarchand
  • 2,068
  • 1
  • 15
  • 27
2

It's because you have sliced the list till -1 which means the last element of the array and is excluded from the sliced array.

To get an array sliced till the end leave the end part of the slice code empty. Like this -

B = Av[int(len(Av)/2):]
SuPythony
  • 875
  • 8
  • 23