简体   繁体   中英

how to remove the last digit in a list if the list contain number last number some were in the list

i need to remove a digit in the given list,But while executing this first digit is removed

python pycharm

l = [4, 2, 6, 4, 7]

l.remove(l[3])

print(l)

expected output: [4, 2, 6, 7] But I get: [2, 6, 4, 7]

要从给定索引的列表中删除项目,请像这样使用list().pop()

l.pop(3)  # Remove the third element.

It has 3 methods to remove an element from python List.

You can read more about list in here

list.pop(3)   # remove 4th element

del list(3)   # remove 4th element

list.remove(value1)  # remove element have value1 in list

Avoid using a direct pop() function if your list is dynamically generating because you don't know the index of elements.

The enumerate() function adds a counter to an iterable. So for each element in a cursor, a tuple is produced with (counter, element) .

list1 = [4, 2, 6, 4, 7]
new_list = []
for index,elm in enumerate(list1):
    if elm not in (list1[:index]):
        new_list.append(elm)

print(new_list)

O/P:

[4, 2, 6, 7]

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