creating python lists on the fly and comparing them
Question: I need to open multiple files and compare the contents of them. The way I am
doing in now is dirty. I want to know an elegant way of doing it. I need to
open multiple files and see the common elements between them.

My code looks like:

    
    
    sample_1=[]
    sample_3=[]
    sample_2=[]
    sample_4=[]
    
    for line in open("sample_EC1.Regions","r"):
        line=line.strip()
        sample_1.append(line)
    
    
    for line in open("sample_EC2.Regions","r"):
        line=line.strip()
        sample_2.append(line)
    
    
    for line in open("sample_EC3.Regions","r"):
        line=line.strip()
        sample_3.append(line)
    
    
    for line in open("sample_EC4.Regions","r"):
        line=line.strip()
        sample_4.append(line)
    
    CommonRegions = list(set(sample_2)&set(sample_3)&set(sample_4)&set(sample_1))
    
    print CommonRegions
    

This code is dirty as if the number of files increases, every time I need to
change the code and if the number of files goes beyond 50, it is very
difficult to edit the code every time.


Answer: 
    total=4
    
    with open("sample_EC1.Regions","r") as f:
        commonregions = {line.strip() for line in f}
    
    for i in range(2,total+1):
        with open("sample_EC"+i+".Regions","r") as f:
            #set comprehension 
            sample = {line.strip() for line in f}
        commonregions = commonregions & sample
    
    print commonregions
    

Instead of writing for loop for each file try to place them in a loop and
perform intersection.

improvements:

  1. Two important improvements, firstly make sure you close files again and secondly don't redundantly convert lists to sets: `with open(...) as f: s = {l.strip() for l in f}`. The thing with the "`for l in f`" is called a set comprehension, the "set comprehension" is an expression that generates a set on the fly 

