[Tutor] Variable Question

Peter Otten __peter__ at web.de
Sun Nov 20 04:25:11 EST 2016


Bryon Adams wrote:

> On 11/18/2016 08:16 PM, Alan Gauld via Tutor wrote:
>> for index, item in enumerate(prefix):
>>     prefix[index] = item[1]
>>
>>
> 
> I forgot about enumerate! That helped me clean up and actually finish my
> next exercise as I was having trouble working for my lists the way I was
> previously.
> 
> Thank you very much =)

enumerate() is a useful tool, but given the code you provide in your 
original post I recommend that you build a new list rather than modifying 
the existing one:

prefix = []
for item in entries:
    prefix.append(item[1])

The above is such a common pattern that Python offers syntactic sugar called 
"list comprehension" to write this:

prefix = [item[1] for item in entries]

In both cases the original entries list is not changed.



More information about the Tutor mailing list