sadmansh
sadmansh

Reputation: 927

How to access the index before i in Python?

struggling a bit understanding how to access indices in Python loops. How would you write this code in Python?

int x = 5;
for (int i = 0; i < s.length; i++) {
    if (s[i] + s[i - 1] == x) {
        System.out.println("Success");
    }
}

So far, I have tried the enumerate method, but I don't think it's working as intended.

x = 5
for i, c in enumerate(s):
    if (i, c + (i - 1), c == x):
        print("Success")

Sorry if this has been asked before, but I couldn't really find a solution to this exact way of handling indices in Python loops. Would really appreciate the help.

Upvotes: 1

Views: 2383

Answers (3)

katamit
katamit

Reputation: 76

considering s to be a sequence, assuming is to be a sequence with numbers and considering the first Java-style code in the first part

s = [0,1,2,3,4,5,..]
x = 5

for i in range(1, len(s)):
    if s[i] +s[i-1] == x:
        print("Success")

Upvotes: 2

Paul Iyobo
Paul Iyobo

Reputation: 54

the enumerate() method splits the lop target in a tuple containing the index, and the element of the target. Unlike c style languages, when you use a for loop in python without the enumerate, i represents the element. This means that you do not have to insert the index in the list when calling it. Your code in python would be like this. s = [1, 2, 3, 4, 5, 6, 7, 8, 9] # the list named s. x = 5 for i in s: if i + i-1 == x: print("success")

Since we're only working with integers, you could do like this as well

x = 5 for i in range(10): if i + i-1 == x: print("success")

Upvotes: 0

Abhinav Upadhyay
Abhinav Upadhyay

Reputation: 2585

for i, c in enumerate(s):
    if c + s[i - 1] == x:

c here will be an element from the list referring to s[i] and i will be index variable. In order to access the element at i-1, you need to use s[i - 1]. But when i is 0, you will be comparing s[0] with s[-1] (last element of s) which might not be what you want and you should take care of that.

Upvotes: 0

Related Questions