1
votes

My current code reads the 1st line, then 3rd, 5th, 7th and so on and adds it to a list.

I want it to read the 2nd, 4th, 6th lines ... and add it to another list.

with open(path) as f:
    content = f.readlines()
content = [x.strip() for x in content[::2]]
3
content[1::2]Burhan Khalid
Kindly add it to answers so i can accept it.Sarah

3 Answers

1
votes

You need to add a start to your slice of 1, e.g. content[1::2]:

with open(path) as f:
    content = f.readlines()

content = [x.strip() for x in content[1::2]]

A better alternative would be to use itertools.islice() to do this, as follows:

from itertools import islice

with open(path) as f_input:
    content = [line.strip() for line  in islice(f_input, 1, None, 2)]
0
votes

You need to start slicing by skipping the first item; here is an example:

>>> list(i)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> list(i[1::2])
[1, 3, 5, 7, 9]

In your code:

content = [x.strip() for x in content[1::2]]
-1
votes

your code should be like that meaning that the slice starts from 1 to the end of the list with a step of two.

with open(path) as f:
    content = f.readlines()

content = [x.strip() for x in content[1::2]]
from itertools import islice

with open(path) as f_input:
    content = [line.strip() for line  in islice(f_input, 1, None, 2)]