MpegEVIL
MpegEVIL

Reputation: 19

list[i] in "for" statement does not return the right values

I have a for statement with the looping variable i, which naturally increases by 1 each time. However, when I run the for statement with a line that gets index i of a certain list, it does something weird. What happens is, it returns very few of the right values and others seemingly randomly.

def allchords(thescale,issev):
    for i in range(len(thescale)):
        makechord((thescale[i]),thescale,issev)

When i=0, it returns thescale[0] correctly.

When i=1, it returns thescale[1] correctly.

When i=2, it returns thescale[3] for some reason.

When i=3, it returns thescale[6]

When i=4, it returns thescale[3]

When i=5, it returns thescale[1]

When i=6, it returns thescale[0]

What the heck is going on?

Okay, here is the entire makechord function:

def makechord(tnc,thescale,issev):
    crdscl=thescale
    for i in range(len(thescale)):
        if crdscl[0] == tnc:
            break
        else:
            tomove=crdscl[0]
            crdscl.pop(0)
            crdscl.append(tomove)

if issev == "y" or "Y":
    thecrd=[(crdscl[0]),(crdscl[2]),(crdscl[4]),(crdscl[6])]
else:
    thecrd=[(crdscl[0]),(crdscl[2]),(crdscl[4])]
print thecrd

Upvotes: 0

Views: 72

Answers (1)

ali_m
ali_m

Reputation: 74162

You are indeed modifying thescale within makechord():

crdscl=thescale

just assigns the name crdscl to thescale, so when you later call

crdscl.pop(0)
crdscl.append(tomove)

you are actually modifying the contents of thescale. An easy way avoid this is by assigning a copy of the contents thescale to crdscl:

crdscl = thescale[:]

Upvotes: 1

Related Questions