This question already has answers here:
What does a colon and comma stand in a python list?
(4 answers)
Closed 1 year ago.
Python doc for built-in function slice is (emphasis mine):
class slice(stop)
class slice(start, stop[, step])
Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by NumPy and other third party packages. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.
What does a[start:stop, i] mean?
I tried it out (in Python 3.6):
a = [1, 2, 3, 4, 5, 6]
a[1:3,1]
but got:
TypeError: list indices must be integers or slices, not tuple
You cannot combine : and , with lists.
: is for direct slicing:
a[1:3:1]
, is used with slice:
a[slice(1,3,1)]
However with objects supporting it (like numpy arrays) you can slice in several dimensions:
import numpy as np
a = np.array([[0,1,3],[3,4,5]])
a[0:1,2]
output: array([3])
Related
If I have an array a, I understand how to slice it in various ways. Specifically, to slice from an arbitrary first index to the end of the array I would do a[2:].
But how would I create a slice object to achieve the same thing? The two ways to create slice objects that are documented are slice(start, stop, step) and slice(stop).
So if I pass a single argument like I would in a[2:] the slice object would interpret it as the stopping index rather than the starting index.
Question: How do I pass an index to the slice object with a starting index and get a slice object that slices all the way to the end? I don't know the total size of the list.
Use None everywhere the syntax-based slice uses a blank value:
someseq[slice(2, None)]
is equivalent to:
someseq[2:]
Similarly, someseq[:10:2] can use a preconstructed slice defined with slice(None, 10, 2), etc.
This question already has answers here:
Array Assignment in numpy / : colon equivalent
(2 answers)
Closed 1 year ago.
I want to slice a multidimensional ndarray but don't know which dimension I will slice on. Lets say we have a ndarray A with shape (6,7,8). Sometimes I need to slice on 1st dimension A[:,3,4], sometimes on third A[1,2,:].
Is there any symbol represent the ":"? I want to use it to generate an index array.
index=np.zeros(3)
index[0]=np.:
index[1]=3
index[2]=4
A[index]
The : slice can be explicitly created by calling slice(None) Here's a short example:
import numpy as np
A = np.arange(9).reshape(3, -1)
# extract the 2nd column
A[:, 1]
# equivalently we can do
cslice = slice(None) # represents the colon
A[cslice, 1]
You want index to be a tuple, with a mix of numbers, lists and slice objects. A number of the numpy functions that take an axis parameter construct such a tuple.
A[(slice(None, None, None), 3, 4)] # == A[:, 3, 4]
there are various ways constructing that tuple:
index = (slice(None),)+(3,4)
index = [slice(None)]*3; index[1] = 3; index[2] = 4
index = np.array([slice(None)]*3]; index[1:]=[3,4]; index=tuple(index)
In this case index can be list or tuple. It just can't be an array.
Starting with a list (or array) is handy in that you can modify values, but it is best to convert it to a tuple before use. I'd have to check the docs for the details, but there are circumstances where a list means something different from a tuple.
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. Slice objects can be used in the construction in place of the [start:stop:step] notation. For example, x[1:10:5,::-1] can also be implemented as obj = (slice(1,10,5), slice(None,None,-1)); x[obj] . This can be useful for constructing generic code that works on arrays of arbitrary dimension.
This is a very simple question but I cannot find documentation anywhere for it. I would like to change the ith element of a list to a slice ("literal colon", like in [:]). Is there any way of doing this?
I have tried doing this:
indexlist = [0] * dim
indexlist[i] = :
This throws a syntax error but I think it gets the point across of what I would like to do.
By a "literal colon" you seem to mean a slice object.
For example:
your_list[i] = slice(None)
To explain what's going on, slicing expressions are actually passed around as tuples of slice objects (or ints, etc).
something[start:stop:step] is equivalent to something[slice(start, stop, step)]. Similarly, something[:] is equivalent to something[slice(None)].
Slicing is implemented through an object's __getitem__ method, so this is also equivalent to something.__getitem__(slice(start, stop, step))
Because you mention numpy in the comments, you might have a look at np.index_exp or np.s_. It lets you quickly create tuples of slices from indexing, and allows you to see what happens.
For example:
import numpy as np
print np.s_[:, 1:5, ::-1, ...]
yields:
(slice(None, None, None), slice(1, 5, None), slice(None, None, -1), Ellipsis)
Which is a tuple of slice objects that you can store and then directly use to slice an object. (e.g. slices = np.s_[0, :, :] and then y = x[slices]).
This question already has answers here:
Understanding slicing
(38 answers)
Closed 8 years ago.
I recently read a code snippets about how to reverse a sequence
>> l = [1,2,3,4,5,6]
>> print l[::-1]
Output
>> [6,5,4,3,2,1]
How to explain the first colon in bracket?
The colons with no values given means resort to default values. The default values for the start index when the step is negative is len(l), and the end index is -len(l)-1. So, the reverse slicing can be written as
l[len(l):-len(l)-1:-1]
which is of the form.
l[start:end:step]
Removing the default values, we can use it in a shorter notation as l[::-1].
It might be useful to go through this question on Python's Slice Notation.
some_list[start:end:step]
When you ommit any of the slicing operands they take on default values.
Default values for start, end and step:
start - the beginning of an indexated iterable which is always of an index 0 when step is positive,
end - the ending index of an indexated iterable which is always its length (following the same convention as range) when step is positive,
step - the default step is always one.
When you're using a minus sign on step omitting other operands you're basically saying "return a reversed list".
EDIT: Funny, but
[1,2,3,4,5,6][5:-7:-1]
returns the same result as
[1,2,3,4,5,6][::-1]
in Python3. Can anyone comment on to why?
That means that default values of start and end actually rest upon the step operand (more specifically its sign).
This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
Closed 5 years ago.
How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.
The method len() returns the number of elements in the list.
Syntax:
len(myArray)
Eg:
myArray = [1, 2, 3]
len(myArray)
Output:
3
len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.
Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).
Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.
If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:
import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2
This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.
import numpy as np
len(a) == np.shape(a)[0]
To get the number of elements in a multi-dimensional array of arbitrary shape:
import numpy as np
size = 1
for dim in np.shape(a): size *= dim
Or,
myArray.__len__()
if you want to be oopy; "len(myArray)" is a lot easier to type! :)
Before I saw this, I thought to myself, "I need to make a way to do this!"
for tempVar in arrayName: tempVar+=1
And then I thought, "There must be a simpler way to do this." and I was right.
len(arrayName)