Skip to content Skip to sidebar Skip to footer

Gathering Every Other String From List / Line From File

I have been scripting for around two weeks, and have just learnt about reading from a file. What I want to do is get every other entry from my original list and store it in a new l

Solution 1:

There are at least a couple ways to accomplish the same thing with less code.

Slice Notation

Python has a way of iterating over every nth element of an array called slice notation. You can replace the entire loop with the following line

Username.extend(File[0::2])

What this basically means is to grab every 2nd element starting at index 0 and add it to the Username array.

The range() function

You can also use a different version of the range() function, that allows you to specify a start, end and step, list so.

for i in range(0, len(File), 2):
    Username.append(File[i])

The range() function is documented here.


Solution 2:

You could use a list comprehension:

input_file:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Python:

>>> with open("input_file") as f:
...     alternates = [line for i, line in enumerate(f) if not i % 2]
... 
>>> alternates
['Line 1\n', 'Line 3\n', 'Line 5\n', 'Line 7\n', 'Line 9\n']

Further reading: the enumerate() built-in function.


Post a Comment for "Gathering Every Other String From List / Line From File"