Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why when I try to remove the last item from the list by x.remove(x[-1]) it removes another item in another order in the list.

Why does it remove the element with index 2 and not the element with index -1 (which is the last element), when I tried this with another list it works, but here it doesn't work, and I don't understand why?!
I tried to convert all elements in the list into string(because some elements is an integar and other is a string), maybe it works, but it didn't

What I have tried:

x = []
for i in range(10):
    y = int(input("Enter your grade: "))
    x.append(y)

z = []
for n in range (len(x)):
    for index in range(len(x)):
        average = (x[n]+x[index])/2
        if n == index:
            continue
        if average >= 0:
            if not(x[n] in z) and not(x[index] in z):
             z.append(x[n])
             z.append (x[index])
             z.append("---")

if z[-1] == "---":
    z.remove(z[-1])

print (z)

for team in z:
    print(team)
```

The result

[1, 2, 3, 4, '---', 5, 6, '---', 7, 8, '---', 9, 10, '---']
1
2
3
4
---
5
6
---
7
8
---
9
10
---

desired result

[1, 2, '---', 3, 4, '---', 5, 6, '---', 7, 8, '---', 9, 10]
1
2
---
3
4
---
5
6
---
7
8
---
9
10
<pre lang="Python"><pre lang="Python"><pre lang="Python">
Posted
Updated 7-Dec-22 5:16am

1 solution

The remove method removes the first instance of the required value, so if you have an array that looks like
[ 1, 2, "---", 3, 4, "---"]
then following the call to remove you get
[1, 2, 3, 4, "---"]
Perhaps you wanted to use pop instead?
Python
if z[-1] == "---":
    z.pop(-1)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900