0

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)

NeuroGreen
  • 21
  • 3
  • Can you not split your string on the \n character to get a list? – shree.pat18 May 14 '22 at 08:56
  • That code doesn't compile, you can't do `listExample[0]` on a string, please share the actual code you run – azro May 14 '22 at 09:01
  • It's not really clear what you are asking. The description plays fast and loose with what is a list or string, what is a word or line. The code as shown does not work - it fails with an error. Guessing what it is supposed to do, you should just be using `str.splitlines` - there is no need for a loop or comprehension. – MisterMiyagi May 14 '22 at 09:03
  • Welcome to Stack Overflow. List comprehensions are for when you want the resulting list's elements to be based on elements from the source, and have at most one element per source element (you can skip source elements by filtering them out). The input here is a string, and the fundamental problem is *splitting the text into words and/or lines*. By understanding the actual difficulty, it becomes much easier to [research](https://meta.stackoverflow.com/questions/261592) a solution. – Karl Knechtel May 15 '22 at 14:10

3 Answers3

2

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']
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
0

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']
BeRT2me
  • 12,699
  • 2
  • 13
  • 31
  • Don't use readlines just to iterate lines. The default iteration of file-like objects is already *lazy* line reading - using readlines needlessly creates a list of all lines in memory. – MisterMiyagi May 15 '22 at 08:13
  • Mind blown, didn't know it worked that way. I've modified my answer~ – BeRT2me May 15 '22 at 19:35
-1

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']]
Thy
  • 468
  • 3
  • 5