[Tutor] For statement

Alfred Milgrom fredm at smartypantsco.com
Fri Mar 12 21:53:59 EST 2004

At 06:31 PM 11/03/04 +0100, you wrote:
>I have a list:
>a= [ 'golden,' , 'poodle,' , 'flat,' , 'retriever,' ]
>I would like to remove the , after the word, with a for statement. 
>However, the result doesn't end up as I like. I end up removing one of the 
>items at the time or getting a TypeError: list indices must be integers error.

You say that "I would like to remove the , after the word, with a for 
Maybe you have a special reason for using a for loop. Andrei has explained 
the logic error in your for loop construct.

Andrei also mentioned list comprehension. You may not be aware of list 
comprehensions that allow you to create new lists from an existing list 
simply and quickly.

A simple general syntax for list comprehension is [modified-x for x in y if 
condition], where:

   x is the name you give each element in your list
   y is your original list
   modified-x is either x (each element as it was in the original list) or 
some modified form of x (any valid Python operation)
   the condition is optional

The output is a new list.

For example, if you are sure that every word in your list a has a comma 
after it, you can write:

newwordlist = [word[:-1] for word in a]

You can also specify conditions in your list comprehension expression. For 
example, if you had words with and without commas and only wanted to find 
the words that had a comma at the end, you could write:

commawords = [word[:-1] for word in a if word.endswith(',')]

There are many more things you can do with list comprehension, and I have 
simplified the syntax a bit here for ease of explanation, but this should 
give you enough to get started with list comprehension.

Hope this helps,

More information about the Tutor mailing list