2

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 list. Is this the best way to do it?

with open("test.txt",mode="r") as myfile:
File = myfile.read().splitlines()

Username = []

for i in range (len(File)):
    if File.index(File[i])%2 == 0 or File.index(File[i]) == 0:
        Username.append(File[i])
print(Username)

Please bear in mind that I have only studied Python for around ten hours so far - I'm quite happy that this even seemed to work.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Kieran Lavelle
  • 446
  • 1
  • 6
  • 22

2 Answers2

5

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.

Community
  • 1
  • 1
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
  • ok thanks, would it have also worked if I just used range(0,len(File),2) or would that not work? – Kieran Lavelle Aug 09 '13 at 21:36
  • That would work, though it results in more code. Choose what is most readable for you. :) I updated my answer to mention using the `range()` function. – Colin Basnett Aug 09 '13 at 21:55
1

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.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • This seems a bit complex compared to the other methods, however I will look it up for some learning :D – Kieran Lavelle Aug 09 '13 at 21:42
  • @KieranLavelle one advantage of this method is that it doesn't store the whole file in a temporary list (which can be useful with large files), because iterating over a file is [lazy](http://en.wikipedia.org/wiki/Lazy_evaluation), and the lines you aren't interested in are just thrown away as the file is read. – Zero Piraeus Aug 09 '13 at 21:49