Gen Tan
Gen Tan

Reputation: 918

Trying to understand ''.join() taking a list in list comprehension

x = "some... random! text?!".split()

x = [''.join(char for char in string if char not in punctuation) for string 
in x]           

I am trying to understand how this list comprehension works by replicating it in a for loop, but I'm unable to re-create it. Here is what I currently have, but it seems incorect. What am I doing incorrectly in my for loop?

for string in x:
    for char in string:
        if char not in punctuation:
            ''.join(char)

Upvotes: 1

Views: 59

Answers (3)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

The list comprehension itself can be directly translated to the following:

_result = []
for string in x:
    _result.append(''.join(char for char in string if char not in punctuation))
x = _result
del _result

Of course, there is no intermediate variables _result. You use a generator expression inside the list comprehension, which is itself like a list-comprehension except it creates a generator. So, something like:

def _g():
    for char in string:
        if char not in punctuation:
            yield char

Putting it all together:

_result = []
for string in x:
    def _g():
        for char in string:
            if char not in punctuation:
                yield char
    _result.append(''.join(_g()))
del _g
x = _result
del _result

But again, no intermediate variables _result and _g are actually created.

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71570

You have to make a list and store the value in there, using append:

l = []
for string in x:
    s = ''
    for char in string:
        if char not in punctuation:
            s += char
    l.append(s)

And now:

print(l)

Is:

['some', 'random', 'text']

Upvotes: 0

iz_
iz_

Reputation: 16593

You can't exactly replicate the generator argument of join perfectly. I would use an intermediate list:

result = []

for string in x:
    to_join = []
    for char in string:
        if char not in punctuation:
            to_join.append(char)
    result.append(''.join(to_join))

With punctuation as from string import punctuation; punctuation = set(punctuation), it outputs

['some', 'random', 'text']

Upvotes: 3

Related Questions