Home  >  Article  >  Backend Development  >  How to Append Strings to a List of Strings in Python?

How to Append Strings to a List of Strings in Python?

DDD
DDDOriginal
2024-10-23 11:29:54467browse

How to Append Strings to a List of Strings in Python?

Concatenating Strings to a List of Strings in Python

Problem:

You desire to append a specific string to each element of a given string list, resulting in a new list with these augmented strings.

Example:

Consider the following initial state:

list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'

After the desired operation, the expected output would be:

list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar']

Solution:

The most straightforward approach to accomplish this is to utilize a list comprehension:

<code class="python">[s + string for s in list1]</code>

In this comprehension:

  • s represents each string in list1.
  • concatenates s with the specified string.

If the efficiency of memory usage is a concern, consider using a generator expression instead, as it provides an iterator rather than a list:

<code class="python">(s + string for s in list1)</code>

The above is the detailed content of How to Append Strings to a List of Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn