Creating file in python indicating if integer in in another list
Question: I have a list of integers, say `[2, 4, 9]`, then I need to create a csv file
like this:

    
    
    1,0
    2,1
    3,0
    4,1
    5,0
    6,0
    7,0
    8,0
    9,1
    

Basically, for each integer, I need to check if the integer is in the list, if
it is I write `1`, otherwise `0`.

I could create a double list, do a for loop, check if the integer is in the
list, and then append the `(i,0)` or `(i,1)` depending on whether `i` is in
the list, but I am sure there is a far more efficient way to do this. These
lists are big, a billion integers or so. I looked if there was something in
numpy to help me, but could not find anything.


Answer: Use [list
comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-
comprehensions) to create your data and use the module
[csv](https://docs.python.org/2/library/csv.html) to write to a csv file.

    
    
    s = set([2, 4, 9])
    lists = [(i, 1) if i in s else (i, 0) for i in range(1, 10)]
    
    # write to a csv file
    import csv
    with open('test.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerows(lists)
    

* * *

Since your data size is quite big, it is better to write to a file while
creating, as shown below.

    
    
    import csv
    
    s = set([2, 4, 9])
    with open('test.csv', 'w') as f:
        writer = csv.writer(f)
    
        for i in range(1, 10000000):
            t = (i, 1) if i in s else (i, 0)
            writer.writerow(t)
    

