I need to remove 0 and 2 elements from the list: {usd},{rur} .

What is the easiest way to do this?

I can not change places, but I set the list - API request. Enumeration of indices separated by commas in the del or remove command does not work. A colon is not an option, because they are not in order.

I wrote this:

 balances = [{usd},{eur},{rur},{gbp}] del (balances[0], balances[1]) 

It turns out that I refer to the lists twice, i.e. to API. It slows down the program, right?

  • And what prevents just create a new list with the necessary values? balances = [balances[1], balances[3] - Vasiliy Rusin
  • In balances, in fact, elements are more than 4 - Kirill
  • But you know exactly the position of the elements you want to delete? - Vasiliy Rusin
  • So for sure ...... - Kirill

3 answers 3

I would do this:

 In [58]: balances = [{'usd'},{'eur'},{'rur'},{'gbp'}] In [59]: del_idx = {0,2} In [60]: balances[:] = [x for i,x in enumerate(balances) if i not in del_idx] In [61]: balances Out[61]: [{'eur'}, {'gbp'}] 
  • one
    set([0,2]) -> {0, 2} ? - gil9red
  • @ gil9red, yeah, thanks! :) - MaxU

As for the multiple deletion. You have a source list, as well as you know the positions of the elements of this list that you want to delete. The decision "in the forehead."

 array = [1,2,2,3,3,4,5,6] # Создаем список ненужных значений unnecessary_values = [a[0], a[2]] for value in unnecessary_values: # Проходим по списку и удаляем. array.remove(value) 

As for the answer to the second question, everything depends on the implementation of the API, most likely you simply transfer the results of the function to the list. The list with the results is in the computer's memory and does not perform requests to the API.

    For the first two elements, del balances[:2] :

     >>> L = [1,2,3] >>> del L[:2] >>> L [3] 

    Related question How to remove every Nth item from the list?

    If the items to delete do not go in succession, to remove items with indices from the indices_to_remove collection:

     for i in indices_to_remove: del L[i] 

    Each del is an O(len(L)) operation, so if the number of elements you want to delete is proportional to the length of the list, then you can use listcomp (list inclusion):

     L[:] = [x for i, x in enumerate(L) if i in indices_to_remove] 

    This creates a new list and replaces all the items in the original list. For a quick search, you can use the set type for the indices_to_remove collection.

    If you want to delete items by value:

     L[:] = [x for x in L if x == value_to_delete] 

    For details, see What is the difference between two for: loops when deleting items during a list traversal .