0

I want to create a new string list from a list of strings using list comprehension. I have this list:

aa = ['AD123', 'AD223', 'AD323', 'AD423']

I want a new list of strings like this:

final = ['AD1', 'AD2', 'AD3', 'AD4']

I've found list comprehension and tried something like this:

 final = map(lambda x: x[:3], aa)

Do I need a for loop to apply this on a list of strings?

Celius Stingher
  • 11,967
  • 4
  • 12
  • 37
Mors
  • 71
  • 4
  • 1
    You have no list comprehension there. If you want to use *map*: `final = list(map(lambda x: x[:3], aa))`, as *map* is a generator. But I'd avoid it. – CristiFati Feb 26 '20 at 16:08
  • _I've found list comprehension and tried something like this:_ And, what happened? _Do I need a for loop to apply this on a list of strings?_ Have you tried that? Have you done any research? – AMC Feb 26 '20 at 18:58
  • Does this answer your question? [How do I get a substring of a string in Python?](https://stackoverflow.com/questions/663171/how-do-i-get-a-substring-of-a-string-in-python) – AMC Feb 26 '20 at 18:59

1 Answers1

3

You can simply use the code you created in your lambda, but for list comprehensions:

new_list = [x[:3] for x in aa]
Celius Stingher
  • 11,967
  • 4
  • 12
  • 37