Python for beginners or not? [was Re: syntax difference]

Mark Lawrence breamoreboy at gmail.com
Mon Jun 25 06:42:27 EDT 2018


On 25/06/18 10:10, Alister via Python-list wrote:
> On Mon, 25 Jun 2018 11:36:25 +0400, Abdur-Rahmaan Janhangeer wrote:
> 
>> i think he means like for a loop to iterate over a list you might do
>>
>> list = [1,2,3]
>> for i in range(len(list)):
>>      print(list[i])
>>
>>
>> but the you might as well go for the simpler :
>>
>>
>> for elem in list:
>>
>>       print(elem)
>>
>> Abdur-Rahmaan Janhangeer https://github.com/Abdur-rahmaanJ
>>
>>
>>
> 
> for i in range(len(list)): is a python anti-pattern it is almost a 100%
> guarantee that you are doing something wrong*
> 
> *as with all rules of thumb there is probably at least 1 exception that
> the python experts will now point out.
> 
> 

The exception is that if you really do need the index, you write:-

for i, elem in enumerate(list):

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list