creating two separate lists read from a file in python
<p>Can i please know how the data from a file can be split into two separate lists. For example,
file contains data as 1,2,3,4;5,6,7 </p>

<pre><code>my code:

for num in open('filename','r'):
  list1 = num.strip(';').split()
</code></pre>

<p>Here , i want a new list before semi colon (i.e) [1,2,3,4] and new list after semi colon (i.e) [5,6,7]</p>

<p>If you are certain that your file only contains 2 lists, you can use a list comprehension:</p>

<pre><code>l1, l2 = [sub.split(',') for sub in data.split(';')]
# l1 = ['1', '2', '3', '4']
# l2 = ['5', '6', '7']
</code></pre>

<p>More generally,</p>

<pre><code>lists = [sub.split(',') for sub in data.split(';')]
# lists[0] = ['1', '2', '3', '4']
# lists[1] = ['5', '6', '7']
</code></pre>

<p>If integers are needed, you can use a second list comprehension:</p>

<pre><code>lists = [[int(item) for item in sub.split(',')] for sub in data.split(';')]
</code></pre>

python python-2.7 python-3.x