0

I am setting a variable to the ith element of the list, but I am getting out of range error even in the first iteration.

# code the max() function


def maxinlist(yourlist):
    first = 0
    second = 0
    duplicatelist = yourlist
    for i in range(0, len(yourlist) - 1):
        first = yourlist[i]

        for j in range(len(yourlist) - 1, 0, -1):
            second = yourlist[j]

            if second > first:
                duplicatelist.pop(i)
            elif first > second:
                duplicatelist.pop(j)

    print(duplicatelist[0])


mylist = [1, 4, 8, 2, 5, 100, 44, 2, 5]
maxinlist(mylist)

2 Answers2

0

make sure you clone your list as you are changing the main list when you change duplicatelist

change the following

duplicatelist = yourlist

to

duplicatelist = yourlist[:]
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
0

In python variable names are the pointers. They do not reflect the actual memory space like in C or C++.

duplicateList=yourList

Here two pointers point to the same memory space. Altering one variable affects the other as well.

duplicatelist = yourlist.copy()

This will create a new memory space for duplicateList as well.