'how to replace values from a list comprehension? [duplicate]
Im trying to make a list from a string with multiple lines. So every new item in the list will be an entire word, I made it, but I was curious to know if it could be done with list comprehension. Im just a beginner*
list:
listExample = """example1
example2
example3"""
I solved it with:
listE = ['']
for n in listExample:
if n == '\n':
listE.insert(0, '')
else:
listE[0] = listE[0] + n
del listE[0]
print(listE)
But, is it possible with list comprehension?
Sorry, I messed it up (forget to include the list listE)
Solution 1:[1]
Easy solution
This simplest way to get this done is with the str.split() method:
>>> listExample.split()
['example1', 'example2', 'example3']
List comprehension version
A list comprehension would is more circuitous but would also get the job done:
>>> [word for word in listExample.splitlines()]
['example1', 'example2', 'example3']
Solution 2:[2]
For some variety, and to show similar syntax as if you were reading a file:
from io import StringIO
listExample = """example1
example2
example3"""
with StringIO(listExample) as f:
the_list = [x.strip() for x in f]
print(the_list)
Output:
['example1', 'example2', 'example3']
Solution 3:[3]
You can add conditional expression to list comprehension to filter elements
For example:
# Exclude word(s) based on index
listE2 = [w for i, w in enumerate(listExample.split()) if i not in [0]]
# Exclude word(s) based on the word
listE3 = [w for w in listExample.split() if w not in ['example3']]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raymond Hettinger |
| Solution 2 | |
| Solution 3 | Thy |
