0

I created a list, a set and a dict and now I want to remove certain items from them

N = [10**i for i in range(0,3)] #range(3,7) for 1000 to 1M
    for i in N:
        con_list = []
        con_set = set()
        con_dict = {}
        for x in range (i): #this is the list
            con_list.append(x)
            print(con_list)
        for x in range(i): #this is the set
            con_set.add(x)
            print(con_set)
        for x in range(i): #this is the dict
            con_dict = dict(zip(range(x), range(x)))
            print(con_dict)

items to remove

n = min(10000, int(0.1 * len(con_list)))
indeces_to_delete = sorted(random.sample(range(i),n), reverse=True)

now if I add this:

for a in indeces_to_delete:
     del con_list[a]
     print(con_list)

it doesn't work

Need to do the same for a set and a dict

Thanks!

  • The problem is: when you delete a certain item a, the list has changed already. So maybe the for loop is the problem... EDIT: stop, I have not recognised your `sorted` – Sosel Nov 14 '17 at 13:13
  • why are you doing all this? what is the end goal? what error are you getting? – Ma0 Nov 14 '17 at 13:15
  • Can't reproduce. Please elaborate on what "it doesn't work" means. – glibdud Nov 14 '17 at 13:20
  • Possible duplicate of [Delete an item from a dictionary](https://stackoverflow.com/questions/5844672/delete-an-item-from-a-dictionary) – Sosel Nov 14 '17 at 13:20
  • @Sosel How is this a duplicate of that? He's already using `del`, and he's not actually deleting anything from a dict in his sample code. – glibdud Nov 14 '17 at 13:22
  • @glibdud He asked for removing in sets, lists and dicts (see title) – Sosel Nov 14 '17 at 13:25
  • @Sosel Sure, but he's already doing what your "dupe" suggests. He needs to provide more info to narrow down what his problem actually is, but it's definitely not learning about `del`. – glibdud Nov 14 '17 at 13:28

1 Answers1

0

You can use pop On a dict:

d = {'a': 'test', 'b': 'test2'}

calling d.pop('b') will remove the key/value pair for key b

on list:

l = ['a', 'b', 'c']

calling l.pop(2) will remove the third element (as list index start at 0)

Beware on set:

s = {'a', 'b', 'c'}

calling s.pop() will remove a random element as discussed here: In python, is set.pop() deterministic?

you should use s.discard('a') to remove element 'a'

More infos here: https://docs.python.org/2/tutorial/datastructures.html

olricson
  • 301
  • 2
  • 8