Append first item into array list when still have space in array list
<p>let's say I need to store 2 elements into a list.</p>

<p>I have 5 items: apple, orange, lemon, papaya, banana</p>

<p>These items i save in a text file, hence there're 5 lines.</p>

<p>I connect the file and start read line by line. Everytime I read a line I append one item in array. Each time the array will fill up by 2 items and when it's full I will empty it and store the next 2 items.</p>

<p>What should I do when it reach the last item? I still have one extra place and I plan to store the 1st item again?</p>

<p>Example:</p>

<pre><code>1st time store
apple, orange, 

2nd time store
lemon, papaya,

3rd time store
banana, apple

4th time store
orange, lemon
</code></pre>

<p>loop........</p>

<p>My current code is unable do so:</p>

<pre><code>def function():
    fo = open("1.txt", "r")
    print "Name of the file: ", fo.name 
    sent_count=0
    ele = []
    while True:
        lines = fo.readlines()   
        for line in lines:
            sent_count+=1
            if(sent_count%4!=0):
                ele.append(lines[sent_count-1])
            if(sent_count%4==0):
                ele.append(lines[sent_count-1])
                for i in ele:
                    print i
                ele = []
                print(sent_count)
                time.sleep(1) 
</code></pre>

<p>Actually you can avoid clearing your <code>ele</code> array. There are some useful built-in modules like <code>collection</code>. It allow you to create your custom array. You can set the <code>maxlen</code> of your array. Moreover you can set left/right append.</p>

<pre><code>d = collections.deque([], maxlen=2)
</code></pre>

<p>means that array <code>d</code> can contain inly two item and if we append one more it will we appended by right side(default). 
Moreover you don't need(if data is not dynamically changed) to reopen your file. Once you opened it you can repeat its lines with the help of `itertools'. It has loads of nice functions I recommend you to look through these modules. </p>

<pre><code>for i in itertools.repeat([1,2,3], 10):
print(i) 
</code></pre>

<p>will print iterator <code>[1,2,3]</code> 10 times.</p>

<p>So the overall code looks like this, but I believe you can optimize it and write more efficient code.</p>

<pre><code>import itertools
import collections

data = ['apple', 'orange', 'lemon', 'papaya', 'banana']
d = collections.deque(maxlen=2)

for i in itertools.repeat(data, 10):
    for item in i:
        d.append(item)
        print(d)
</code></pre>

<p>try it and see the output. Good luck!
By the way just make some changes so that it works for <code>python 2.7</code>. There is almost no difference besides <code>print</code> function. <code>python 2.7</code> also has these modules.</p>

python arrays python-2.7 loops