-1

`

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?

1 Answers1

0
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

Yash Mehta
  • 2,025
  • 3
  • 9
  • 20