This question already has answers here:
Understanding slicing
(38 answers)
Closed 5 years ago.
I am very new to Python and I encountered one issue that I cannot understand. Let say I have string variable:
myVar = "abcdefgh"
I want to display it backward, no problem:
print(myVar[::-1])
and I get hgfedcba. Nothing surprising here. I should get the same with this somewhat verbose code:
print(myVar[len(myVar)-1:0:-1])
but this time the result is hgfedcb. Then I have tried not to subtract 1 from len(myVar) and the result was exactly the same. I do not understand why, especially that lines:
print(myVar[::1])
print(myVar[0:len(myVar):1])
display the same results.
So, my question is why print(myVar[len(myVar):0:-1]) does not display "a"?
The verbose equivalent of print(myVar[::-1]) would be:
print(myVar[-1:-1-len(myVar):-1])
# Or
# print(myVar[len(myVar)-1:-1-len(myVar):-1])
# but this makes the the length invariant less obvious
Note that the stop parameter is exclusive, and in order to get to the actual -1, you have to additionally subtract the full length as negative indexing starts at the end of the sequence. Note also how (stop-start)*step is still the length of the slice.
Related
This question already has answers here:
Understanding slicing
(38 answers)
Closed 1 year ago.
First time using StackOverflow, apologies in-case of any issues.
In python,
list[::-1] returns the reversed list
list[0:len(list)+1] returns the complete list
So why list[0:len(list)+1:-1] returns an empty list?
Further, for a list l= [0,1,2,3,4,5], if I want like [4,3,2]:
Trying l[2:5:-1], returns an empty list. But l[2:5][::-1] works.
Can anyone explain why this is happening? Or what is python actually doing when we slice a list, with a value for step?
Thanks in advance :)
some_list[start:stop:step] means give me elements starting at start and incrementing by step until you hit stop.
Well, if you start at 0 and increment by -1, you never actually reach the stop.
This question already has an answer here:
Inconsistent behavior in np.arange?
(1 answer)
Closed 2 years ago.
I encountered a question when I wanted to generate a numpy array using numpy.arange.
For example, I want to generate an array that contains 3862 elements:
array1=numpy.arange(3.5678,3.5678+3862*0.0001,0.0001)
But the shape of array1 is (3863,). And what made me more confused is this:
In:
numpy.arange(3.5678,3.5678+3860*0.0001,0.0001).shape
numpy.arange(3.5678,3.5678+3861*0.0001,0.0001).shape
numpy.arange(3.5678,3.5678+3862*0.0001,0.0001).shape
numpy.arange(3.5678,3.5678+3863*0.0001,0.0001).shape
Out:
(3861,);(3861,);(3863,);(3863,)
Why did this happen? Due to the precision?
Many thanks!
According to numpy doc:
For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.
And also:
stop number:
End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.
You can check out this duplicate question or this one for more detail and info on how to deal with the situation.
This question already has answers here:
Uncomfortable output of mode() in pandas Dataframe
(4 answers)
Closed 4 years ago.
train['Gender'].fillna(train['Gender'].mode()[0], inplace=True)
I got this code in one of my basic data science course. I wanted to understand, what is the significance of "[0]" after mode() in this. I would really appreciate the answer.
Thanks!
Mode documentaion
The mode() return 2 value, first is mode value second is count. So train['Gender'].mode()[0] means get the mode value of train['Gender'].
The notation [0] means that the thing before it (mode() in this case) is a collection, a list, an array, ..., and you are taking the first element.
In case you need more information, you need to include the rest of the source code (preferably by editing your question), explaining the exact meaning of the mentioned objects.
This question already has answers here:
Python. Will TWO condition checked, If `ONE == True`? [duplicate]
(3 answers)
Closed 5 years ago.
I have a multi-part boolean expression in a piece of python code, part of which involves a call to a random number generator and evaluating an expoenential of a sum of a 2d array. Since this is buried deep in nested loops I want to avoid checking that last part if at all possible, since it's computationally expensive.
if self.B == 0 or (np.sign(self.B) == -sign) or (np.random.rand() < np.exp(-2*sign*self.B*np.sum(cluster))):
do stuff
If either of the first two expression are true, will the random number generator still be called? Or is it guaranteed to evaluate those parts in order and stop once it finds one that is true?
I can always make it explicit by breaking it up, but it seems like something I should probably know anyway.
In if A or B, B is only evaluated if A is false.
This concept is called short circuiting, and you can read a little about it here.
The idea is that you go from left to right until a result is determined. Once that's the case, you stop.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
reverse a string in Python
I tried searching the python documentation for a certain slicing exapmle
lets say I have this string
a = "ABCD"
when I write:
a[::-1]
I get the reversed string
"DCBA"
I can't understand how exectaly it works. None of the examples I saw were with two colons. what does it mean? how does it work?
thank you!
The full syntax of a slicing is
a[start:stop:step]
The step value denotes by how much to increase the index when going from one element of the slice to the next one. A value of -1 consequently means "go backwards". If start and stop are omitted as in your example, the default is to use the whole string (or more generally, the whole sequence, as this also works for lists and tuples).