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?

3
  • 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. Commented Feb 26, 2020 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? Commented Feb 26, 2020 at 18:58
  • Does this answer your question? How do I get a substring of a string in Python? Commented Feb 26, 2020 at 18:59

2 Answers 2

3

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

new_list = [x[:3] for x in aa]
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly, just trying to to be too fancy with lambda. Thanks for the help Celius
It might fancier, but way less performant! Make performance the new fancy ;)
0

Solution provided by @celius-stingher is concise and perfect.

I want to discuss the approach to problem-solving and how to think programmatically:

  1. Understand the problem and identify input/output.
# Input list of strings
input = ['AD123', 'AD223', 'AD323', 'AD423']

# Output list of modified strings. Choose the right data structure for output.
output = []
  1. Write Pseudocode
for each word in words:
    take the first three characters of word
    add the three characters to first_three_chars list
  1. Now let's implement a step-by-step solution
# Input list of strings
input = ['AD123', 'AD223', 'AD323', 'AD423']

# Output list to store modified strings
output = []

# Loop through each word in the input list
for item in input:
    # Extract the first three characters of the item using string slicing
    first_three = word[:3]
    
    # Add the modified word to the output list
    output.append(first_three)

# Print the result
print(first_three_chars)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.