Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What does for x in A[1:] mean? [duplicate]

Tags:

python

I was trying to understand Kadane's algorithm from Wikipedia, when I found this:

def max_subarray(A):
    max_ending_here = max_so_far = A[0]
    for x in A[1:]:
        max_ending_here = max(x, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)
    return max_so_far

I'm not familiar with Python. I tried to google what this syntax does but I couldn't find the right answer because I didn't know what's it called. But, I figured A[1:] is the equivalent of omitting A[0], so I thought for x in A[1:]: is equivalent to for(int i = 1; i < A.length; i++) in Java

But, after changing for x in A[1:]: to for x in range(1,len(A)), I got the wrong result

Sorry if this is a stupid question, but I don't know where else to find the answer. Can somebody tell me what this syntax does and what is it called? Also, could you give me the equivalent of for x in A[1:]: in Java?

like image 861
Margo Eastham Avatar asked Dec 26 '14 03:12

Margo Eastham


People also ask

What does 1 :] mean in Python?

s[1:] is 'ello' -- omitting either index defaults to the start or end of the string. s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way to copy a sequence like a string or list)

What does for X mean in Python?

Show activity on this post. For x in range(3) simply means, for each value of x in range(3), range(3) = 0,1,2. As it is range(3), the loop is looped three times and at each time, value of x becomes 0, then 1 and then 2.

What does X for X in mean in Python?

This is just standard Python list comprehension. It's a different way of writing a longer for loop. You're looping over all the characters in your string and putting them in the list if the character is a digit.

What does x += 1 do in Python?

With x = x + 1 , the interpreter will treat it like x = x. __add__(1) , while x += 1 will be x = x. __iadd(1) , which can be much more efficient because it doesn't necessarily need to make a copy of x . x += 1 actually becomes x = x.


1 Answers

Here are some of the example that I have tried

>>> a=[1,5,9,11,2,66]

>>> a[1:]
[5, 9, 11, 2, 66]

>>> a[:1]
[1]

>>> a[-1:]
[66]

>>> a[:-1]
[1, 5, 9, 11, 2]

>>> a[3]
11

>>> a[3:]
[11, 2, 66]

>>> a[:3]
[1, 5, 9]

>>> a[-3:]
[11, 2, 66]

>>> a[:-3]
[1, 5, 9]

>>> a[::1]
[1, 5, 9, 11, 2, 66]

>>> a[::-1]
[66, 2, 11, 9, 5, 1]

>>> a[1::]
[5, 9, 11, 2, 66]

>>> a[::-1]
[66, 2, 11, 9, 5, 1]

>>> a[::-2]
[66, 11, 5]

>>> a[2::]
[9, 11, 2, 66]

I think you can understand more by this examples.

like image 94
Saurabh Lende Avatar answered Oct 19 '22 14:10

Saurabh Lende