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?
#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


Messages In This Thread
A strange list, how does this work? - by Pedroski55 - May-13-2020, 10:52 PM
RE: A strange list, how does this work? - by snippsat - May-13-2020, 11:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extending list doesn't work as expected mmhmjanssen 1 52 Less than 1 minute ago
Last Post: deanhystad
  Strange behavior list of list mmhmjanssen 3 270 4 hours ago
Last Post: mmhmjanssen
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,406 May-22-2023, 10:39 PM
Last Post: ICanIBB
  Beginner: Code not work when longer list raiviscoding 2 860 May-19-2023, 11:19 AM
Last Post: deanhystad
  How to work with list kafka_trial 8 2,090 Jan-24-2023, 01:30 PM
Last Post: jefsummers
  how does .join work with list and dictionaries gr3yali3n 7 3,361 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,329 Jul-22-2019, 08:25 PM
Last Post: umut3806
  Lists inside lists work strange jdrp 5 3,424 Jun-07-2018, 02:06 PM
Last Post: jdrp
  Example of list comprehensions doesn't work Truman 17 10,962 May-20-2018, 05:54 AM
Last Post: buran
  List 3 dimensions reference does not work Mario793 1 2,671 Mar-02-2018, 12:35 AM
Last Post: ka06059

Forum Jump:

User Panel Messages

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