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!
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
-
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.
-
//
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 /
.
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!
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
-
The subscript operator
:
can be thought of to take two arguments,start:stop
. If you leavestart
blank it will take all values up tostop
, and vice versa. -
//
specifies floor div, which always rounds down, that way we are always subscripting anint
not afloat
. Note this is only for Python 3, in Python 2 floor div is the standard and is invoked by a single foward slash/
.