This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
good primer for python slice notation
I am a little confused as to what the slice operator does in python. Can anyone explain to me how it works?
The slice operator is a way to get items from lists, as well as change them. See http://docs.python.org/tutorial/introduction.html#lists.
You can use it to get parts of lists, skipping items, reversing lists, and so on:
>>> a = [1,2,3,4]
>>> a[0:2] # take items 0-2, upper bound noninclusive
[1, 2]
>>> a[0:-1] #take all but the last
[1, 2, 3]
>>> a[1:4]
[2, 3, 4]
>>> a[::-1] # reverse the list
[4, 3, 2, 1]
>>> a[::2] # skip 2
[1, 3]
The first index is where to start, the (optional) second one is where to end, and the (optional) third one is the step.
And yes, this question is a duplicate of Explain Python's slice notation.
Related
I have a list that contains many elements, where each element represents an input file, that I want to dynamically subset using the values contained within another list. For example, I have some code that dynamically generates lists that I want to use to define the sub-samples such as
[0, 1, 2, 3]
and
[1, 2, 3, 4]
But I want to use the start and end elements of each of these lists to define an slice range to be applied to another list. In other words, I want the two above lists to be converted into slices that look like this
[0:3]
and [1:4]
But I don't know how to do this, and to be honest I'm not even sure the correct terminology to use to search for this. I have tried searching stack overflow for 'dynamically generate slices from lists' or even 'dynamically generate data slice' (an variants that I can think of along those lines) without any success.
Here are a few more details:
thislist = ['2019/12/26/fjjd', '2019/12/26/defg', '2020/01/09/qpfd', '2020/01/09/tosf', '2020/01/16/zpqr', '2020/01/15/zpqr', '2020/01/15/juwi']
where someIndexSlice is
[0:3]
and generated from a list that looks like this
[0,1,2,3]
thislist[someIndexSlice] = ['2019/12/26/fjjd', '2019/12/26/defg', '2020/01/09/qpfd', '2020/01/09/tosf']
So my questions are:
How can I accomplish this?
What sort of terminology should I use to describe what I am trying to accomplish?
Thanks
You can use the built-in slice function:
>>> lst = [0, 1, 2, 3]
>>> as_slice = slice(lst[0], lst[-1], lst[1] - lst[0])
>>> as_slice
slice(0, 3, 1) # which is same as [0:3]
And then to check if it works correctly:
>>> test = [1, 5, 3, 7, 8]
>>> test[as_slice]
[1, 5, 3]
>>> test[0:3]
[1, 5, 3]
NOTE:
This implementation assumed your lists are equidistant, and sorted.
This question already has answers here:
Understanding slicing
(38 answers)
Closed 3 years ago.
Why for example when slicing a list with square brackets in this way
spam = [1, 2, 3]
When we print(spam[0:2]) the 3 is not typed while the index of that is 2?
This style of indexing is just very beautiful and comfortable. There're lots of cases where this can be useful. The easiest one is when you have to do something on two halves of an array:
spam = [1, 2, 3, 4, 5]
center_index = len(spam) / 2
func(spam[center_index:])
func(spam[:center_index])
In this example, you don't have to think about +1/-1
Because Python slicing is inclusive # start and exclusive # the end
This question already has answers here:
Access multiple elements of list knowing their index [duplicate]
(11 answers)
Closed 5 years ago.
It's fairly simple to articulate problem, but I'm not 100% sure that I have my lingo right. Nonetheless, conceptually "cherry picking" is suitable to describe the slice I have in mind. This is because I simply want to access (cherry pick from all elements) two distant elements of a list. I tried this:
my_list[2,7]
So I was expecting it to return only 2 elements, but instead I got the error:
list indices must be integers, not tuples.
I searched this error, but I found it was actually a very general error and none of the problems that instigated this error were actually for my type of problem.
I suppose I could extract the elements 1 at a time and then merge them, but my gut tells me there is a more "pythonic" way about this.
Also a slightly more complicated form of this problem I ran into was building a new list from an existing list of lists:
new_list = []
for i in range(len(my_list)):
new_list.append(my_list[i][2,7])
Normally I would just use operator.itemgetter for this:
>>> my_list = list(range(10))
>>> import operator
>>> list(operator.itemgetter(2, 7)(my_list))
[2, 7]
It also allows getting an arbitrary amount of list elements by their indices.
However you can always use NumPy (that's an external package) and it's integer slicing for this (but it won't work for normal Python lists, just for NumPy arrays):
>>> import numpy as np
>>> my_arr = np.array(my_list)
>>> my_arr[[2, 7]]
array([2, 7])
In [1]: myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]: myList[2:8:5]
Out[2]: [2, 7]
myList[start:end:stride]
Hope this helps.
This question already has answers here:
Understanding slicing
(38 answers)
Closed 6 years ago.
I'm a beginner attempting to learn Python. I am familiarising myself with the list data type; I've defined the following list:
>>> numbers = [1, 2, 3, 4]
Typing:
>>> numbers[0]
1
>>> numbers[1]
2
>>> numbers[2]
3
>>> numbers[3]
4
Given this, why do I get the following when I attempt to retrieve the following list elements:
>>> numbers[0:3]
[1, 2, 3]
Why isn't the list element '4' included in the response from the interpreter?
Thank you for your help.
Slice notation does not include the last element (similar to the range() function in that respect). If you want to include the last element, simply omit an index. Also, the default start is the beginning, so you don't need 0 there either:
>>> numbers[:]
[1, 2, 3, 4]
Note that this is a (shallow) copy of numbers. If you save a reference to it, you can mutate it without affecting the original numbers.
That's how slicing works in Python. To quote a tutorial:
Note how the start is always included, and the end always excluded.
This makes sure that s[:i] + s[i:] is always equal to s.
The example uses a string, but slicing works the same way with lists.
numbers[0:3] list from 0 up to 3 but 3 is excluded (like range(0,3))
I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list and insert something into it to make it bigger? Thanks
>>> a = [1,2,3]
>>> a[:0] = [4]
>>> a
[4, 1, 2, 3]
a[:0] is the "slice of list a beginning before any elements and ending before index 0", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original list with those elements. You could also do the same anywhere else in the list by specifying a zero-width slice (or a non-zero width slice, if you want to also replace existing elements):
>>> a[1:1] = [6,7]
>>> a
[4, 6, 7, 1, 2, 3]
To prevent this from happening you can subclass the builtin list and then over-ride these methods for details refer here