Luminous_Path
Luminous_Path

Reputation: 130

Python how to iterate through a list and compare lists of strings found within

If I have a nested list that looks like this:

bigstringlist = [['rob', 'bob', 'sam', 'angie'], ['jim', 'angie', 'tom', 'sam'], ['sam', 'mary', 'angie', 'sally']]

How do I iterate through this list and extract a list of names that appear in all the nested lists? i.e.:

finallist = ['sam', 'angie']

Would this be better accomplished by typecasting this nested list as a set?

Upvotes: 2

Views: 609

Answers (2)

pillmuncher
pillmuncher

Reputation: 10162

A variation on singularity's solution, maybe a little faster:

bigstringiter = iter(bigstringlist)
reduce(set.intersection, bigstringiter, set(next(bigstringiter)))

Upvotes: 0

mouad
mouad

Reputation: 70021

reduce(set.intersection, map(set , bigstringlist))

Upvotes: 11

Related Questions