serilain
serilain

Reputation: 451

iterate through second value of each nested list in python

Probably something really simple, but I'm having some real trouble with it. I have a list that's like so:

[[1, 2500],[3,4319],[8,3292],[3,34590]]

where the first value in each nested list is a score of some kind and the second value is the user id that the score corresponds to.

I'm trying to do some simple arithmetic on the list to remove all user IDs in a second list. however, I'm finding that I can't address only the second element of each nested list.

newlist = list(set(oldlist[][1]) - set(to_be_removed))

am I trying to get too creative with the brackets, or am I just missing something very simple?

Upvotes: 1

Views: 2233

Answers (2)

R Hyde
R Hyde

Reputation: 10409

Something like this?

old_list = [[1, 2500],[3,4319],[8,3292],[3,34590]]
removals = set([2500, 34590])
new_list = [[x, y] for x, y in old_list if y not in removals]

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601669

Using a list comprehension would be the easiest solution here:

new_list = [x for x in old_list if x[1] not in to_be_removed]

Upvotes: 2

Related Questions