-4

I know that there is another answer to this but that's for complex users. I'm a basic python user who started a couple of days ago. So I need a simple answer

Im trying to understand this line of code. Mostly the enumerate part. Could someone please what enumerate does.

f = open("solutions.txt", "r")
searchlines = f.readlines()
for i, line in enumerate(searchlines):

Thanks in Advance

LoY4l Frost
  • 9
  • 1
  • 8

1 Answers1

0

enumerate is used to generate a line index, the i variable, together with the line string, which is the i-th line in the text file. Getting an index from an iterable is such a common idiom on any iterable that enumerate provides an elegant way to do this. You could, of course, just initialize an integer counter i and increment it after each line is read, but enumerate does that for you. The main advantage is code readability: the i variable initialization and increment statements would be book-keeping code that is not strictly necessary to show the intent of what that loop is trying to do. Python excels at revealing the business-logic of code being concise and to the point. You can look at Raymond Hettinger's presentation to learn more about idiomatic python from these excellent notes.

Cyb3rFly3r
  • 1,321
  • 7
  • 12
  • Thanks for the help. Unfortunately I didn't understand most of it. As I said I'm a beginner & still don't know much about python. Can you put it in any simpler terms? – LoY4l Frost Apr 07 '16 at 22:29
  • `f = open("solutions.txt", "r")` opens the file and assigns to f, then the `f.readlines()` reads all the lines in the files and puts them in a list, assigned to the `searchlines` variable. A list in Python is an `iterable` object. The following for-loop (which in other languages is called foreach) iterates through each line in the list. Enumerate gives you something more: the index i which correspond to the index of the line in the list (and thus also the line number, although starting at 0). You should try that code by adding: print('{0}: {1}'.format(i+1, line)) in the loop. – Cyb3rFly3r Apr 07 '16 at 22:51
  • Thanks so much. & I don't think i'd change it now as i've finally git it to work – LoY4l Frost Apr 09 '16 at 12:05