Rob
Rob

Reputation: 11

Editing list containers

Presently I have build a program that counts certain critera in a list which stores the data in a dictionary then at the end I add it to a new list.

count_occurances = Counter(lister_agent).values()
my_list.append(list(count_occurances))

I may get something like the list below with two containers in it:

my_list = [[123,1,3],[258,9,7]]

The problem I then have is editing the containers in the list based off different parameters. For example editing container [0]:

for y in my_list[0]:
    if y > 100:
        my_list.remove(y)

Doing this I get the error:

ValueError: list.remove(x): x not in list

Where am I going wrong?

Upvotes: 0

Views: 48

Answers (2)

Al-Taie
Al-Taie

Reputation: 258

You have nested list so you should use nested for loop too.

my_list = [[123, 1, 3], [258, 9, 7]]

for lst in my_list:
    for i in lst:
        if i > 100:
            lst.remove(i)

print(my_list)

output:

[[1, 3], [9, 7]]

Upvotes: 0

shmuel wachtfogel
shmuel wachtfogel

Reputation: 38

your for loop is going through my_list[0] which is [123,1,3]. meaning y will be 123 then 1 then 3. You are trying to do mylist.remove(123). since 123 is not in my_list ([[123,1,3],[258,9,7]]) it doesn't get removed. 123 only exists in my_list[0]

Upvotes: 1

Related Questions