Set an array equal to the first half of its entries in python

Question:

In python:

How do I set an array equal to it’s first half only, deleting all the entries past the first half?

Things I’ve Already Tried

a = a[0 ; len(a)/2 ]

This doesn’t seem to work!

Asked By: jackzellweger

||

Answers:

Easily done by indexing the array from all values before the half point.

your_list = your_list[:len(your_list)//2]

In practice

your_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print(your_list)
your_list = your_list[:len(your_list)//2]
print(your_list)

Out

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Tricks

  1. The subscript operator : can be thought of to take two arguments, start:stop. If you leave start blank it will take all values up to stop, and vice versa.

  2. // specifies floor div, which always rounds down, that way we are always subscripting an int not a float. Note this is only for Python 3, in Python 2 floor div is the standard and is invoked by a single foward slash /.

Answered By: Jason
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.