Python Forum
A strange list, how does this work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A strange list, how does this work?
#1
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??
Reply
#2
(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']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,355 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Beginner: Code not work when longer list raiviscoding 2 831 May-19-2023, 11:19 AM
Last Post: deanhystad
  How to work with list kafka_trial 8 2,048 Jan-24-2023, 01:30 PM
Last Post: jefsummers
  how does .join work with list and dictionaries gr3yali3n 7 3,330 Jul-07-2020, 09:36 PM
Last Post: bowlofred
Question Why does modifying a list in a for loop not seem to work? umut3806 2 2,311 Jul-22-2019, 08:25 PM
Last Post: umut3806
  Lists inside lists work strange jdrp 5 3,381 Jun-07-2018, 02:06 PM
Last Post: jdrp
  Example of list comprehensions doesn't work Truman 17 10,891 May-20-2018, 05:54 AM
Last Post: buran
  List 3 dimensions reference does not work Mario793 1 2,655 Mar-02-2018, 12:35 AM
Last Post: ka06059
  Trying to figure out how list comprehensions work tozqo 4 4,028 Jul-11-2017, 01:26 PM
Last Post: ichabod801
  Why list(dict.keys()) does not work? landlord1984 5 13,676 Feb-02-2017, 05:52 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020