How to create a new string list from a list of strings excluding one variable?

Viewed 1527

I have a list of strings and I'm trying to iterate through it and create each iteration a new list without one of the strings. I tried the following:

tx_list = ['9540a4ff214d6368cc557803e357f8acebf105faad677eb06ab10d1711d3db46', 'dd92415446692593a4768e3604ab1350c0d81135be42fd9581e2e712f11d82ed',....]
for txid in tx_list:
    tx_list_copy = tx_list
    tx_list_without_txid = tx_list_copy.remove(txid)

But each iteration the new list is empty.

3 Answers

You may try this:

for i in range(len(tx_list)) :
    tx_list_without_txid = tx_list[:i] + tx_list[i+1:]
    # do something with the new list...

The statement:

tx_list_copy = tx_list

does not copy the list but it refers to the same memory object: tx_list and tx_list_copy are different references to the same memory object list. This means that if you edit the first one, the second one will be edited too.
Instead, in order to copy the original list, you should use the .copy() method:

for txid in tx_list:
    tx_list_copy = tx_list.copy()     # copy the original list
    tx_list_copy.remove(txid)         # remove the txid element, this is already the list without the txid element

Then, to remove the txid element from tx_list_copy, you could use the .remove() method, which removes the element in the tx_list_copy, so this is already the list you need.

If you want to create multiple lists then this won't work you'll need to create a dictionary:

list_box = {}
for txid in tk_list:
    list_box[txid] = tx_list.copy()
    list_box[txid].remove(txid)

this will create a new list with name list_box[txid] where txid is the element that dosen't exists in the list(for better understanding). Hope it will help!

Related