简体   繁体   中英

Removing element from a list on python based on position?

I was just wondering how would I be able to remove a part of a list purely based on position.

rando = keywords[random.randint(0, 14)]
h = 0
for h in range(len(keywords)):
    if rando == keywords[h]:
        position = h

realAns = definitions[position]

I tried

rando.remove[h] 

but it didn't seem to work :(

What code would I be able to use to remove that keyword (not definition) once correct. Thanks.

Use del and specify the element you want to delete with the index .

>>> a=[i for i in range(1,11)]
>>>a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> del a[0]
>>> a
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 

In addition you can also use pop , pop return deleted element .

>>> a=[i for i in range(1,11)]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a.pop(1)
2
>>> a
[1, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 

If you not specified any argument in pop it removes the last item.

>>> a=[i for i in range(1,11)]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a.pop()
10
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

If you also want to get what your removing, you can do:

rando.pop(h)

Otherwise just do:

del rando[h]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM