This is a static archive of the Python wiki, which was retired in February 2026 due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

I want to change an element in an array during a loop:

 lines=open("/etc/fstab","r").readlines()
 for line in lines:
    if line.split()[1]=="/": 
       line="# "+line

Now that does not change the contents of the array (commenting out a particular line in the file). I know you can easily make a loop counter, an d add i=i+1, but isn't there a better way?

== Answer== Try using the enumerate builtin.

 lines=open("/etc/fstab","r").readlines()
 for index,line in enumerate(lines):
    if line.split()[1]=="/": 
       lines[index] ="# "+line

When answering questions, add the CategoryAskingForHelpAnswered category when saving the page. This will move the link to this page from the questions section to the answers section on the Asking for Help page.


CategoryAskingForHelp CategoryAskingForHelpAnswered


2026-02-14 16:06