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
  • 17,835
  • 6
  • 23
  • 53
Mors
  • 71
  • 5
  • 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

2 Answers2

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
  • 17,835
  • 6
  • 23
  • 53
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)
codewhat
  • 11
  • 1