Python Forum
A strange list, how does this work? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: A strange list, how does this work? (/thread-26794.html)



A strange list, how does this work? - Pedroski55 - May-13-2020

I'm just an amateur at Python.

I'm reading a book called Python Automation Cookbook. The text contains some numbers to be replaced with X.

The book has this, which works fine:

redacted = [''.join('X' if w.isdigit() else w for w in word) for word in words]
Everything seems to be backward: for loop last, if clause after the condition, yet it does exactly what it should and all the code is in list brackets []

Is this some new use of a list??


RE: A strange list, how does this work? - snippsat - May-13-2020

(May-13-2020, 10:52 PM)Pedroski55 Wrote: Is this some new use of a list??
It's list comprehensions not new as it has been a part Python language for 20-years PEP 202.

If break it to ordinary loop and append to a new list way,it would look look like this.
>>> words = 'hello123 world'
>>> new_lst = []
>>> for w in words:    
...     if w.isdigit():        
...         new_lst.append('X')
...     else:    
...         new_lst.append(w)
...         
>>> new_lst
['h', 'e', 'l', 'l', 'o', 'X', 'X', 'X', ' ', 'w', 'o', 'r', 'l', 'd']
>>> words = 'hello123 world'
>>> [''.join('X' if w.isdigit() else w for w in word) for word in words]
['h', 'e', 'l', 'l', 'o', 'X', 'X', 'X', ' ', 'w', 'o', 'r', 'l', 'd']