Anyone knows python..?

Hey folks,
I need help with my python code
Here is the list:-
list=[[“Doe”,1,74.0],[“John”,2,65.0],[“Lorem”,3,99.0]]

I want to delete the whole sublist with an index of the middle number
for eg. I’ll give input as 2 and delete item should be [“John”,2,65.0].
so list will be
list=[[“doe”,1,74.0],[“Lorem”,3,99.0]].

Thanks in advance

2 Likes

list.pop(1)
Index starts from 0.
So to delete 2nd sublist, use index 1.

3 Likes

Good work @astrid01 and good of you to share the link for the op to reference it later :+1:

2 Likes

There are many ways to do this.

a=[['Doe',1,74.0],['John',2,65.0],['Lorem',3,99.0]]

Method 1:

del a[1]

Try it online!

Method 2:

a.pop(1)

Try it online!

Method 3:

a=[a[i] for i in range(len(a)) if i != 1]

Try it online!

3 Likes

Just wanted to know can we delete any element of a sublist according to the input
like: I enter 2 and 1 so it should remove Lorem from the 3rd sublist

2 Likes

Yes you can.

list[element].pop(nested_element)

list[2].pop(1)

2 Likes
a=[['Doe',1,74.0],['John',2,65.0],['Lorem',3,99.0]]

print(a[2].pop(0)

print(a) #gives [['Doe', 1, 74.0], ['John', 2, 65.0], [3, 99.0]]
2 Likes

Just do it like

try: # because the input may go beyond the bounds
    del list[int(input())] 
    # or list.pop(int(input()) 
    # or list=[list[i] for i in range(len(list)) if i != int(input())]
except:
    print('The index you entered is out of bounds')