How does this code work? It gives me 24 as output

Question:

`

n = [2, 4, 6, 8]
res = 1
for x in n[1:3]:
  res *= x

print(res)

`

I don’t understand how this code works or what it does. I believed that it should multiply x (which is chosen randomly from 4, 6, or 8) by res, but it doesn’t do that.

I thought that the n[1:3] meant numbers 1 and 3 (4 and 8 in the data set respectively) but that multiplies to 32. I don’t know what the x is now.
Can anyone explain how it works?

Asked By: MJwaterskis

||

Answers:

The for x in n[1:3] uses the numbers between the 1st and the one before the 3rd one

In this case it will use the 4 (position 1) and the 6 (position before the 3rd)

In order to do from 4 to 8 you need to use n[1:4]

I think that you want to multiply only the 4 and the 8 tho, in that case that implementation of the for loop would not work for you

Answered By: Alexander García
n = [2, 4, 6, 8]
ind=[0, 1, 2, 3]   #indexing of list

so,

n[1:3] = [4,6] [It includes 1 and 2 index exclude 3rd index] (i.e when slicing left side is included right side excluded)

Dry Run like..

for x in [4,6]:
    res*=x

so in first iteration  res=1*4 .. res=4
in second iteration res=4*6 .. res=24

print(res). #24

To know more about slicing..!

Credit to: @Greg Hewgill @Mateen Ulhaq

Note: a is a list

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array
a[start:stop:step]   #When you have to jump specific index each time you can use step

You can follow up answer -> Understanding Slicing

Answered By: Yash Mehta
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.