Search code examples
pythonstringlistsubstringlist-comprehension

Substring a list of strings using list comprehension


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?


Solution

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

    new_list = [x[:3] for x in aa]