Madno
Madno

Reputation: 910

Extract substrings from a list into a list in Python

I have a Python list like:

['[email protected]', '[email protected]'...]

And I want to extract only the strings after @ into another list directly, such as:

mylist = ['gmail.com', 'hotmail.com'...]

Is it possible? split() doesn't seem to be working with lists.

This is my try:

for x in range(len(mylist)):
  mylist[x].split("@",1)[1]

But it didn't give me a list of the output.

Upvotes: 1

Views: 14253

Answers (2)

calico_
calico_

Reputation: 1221

You're close, try these small tweaks:

Lists are iterables, which means its easier to use for-loops than you think:

for x in mylist:
  #do something

Now, the thing you want to do is 1) split x at '@' and 2) add the result to another list.

#In order to add to another list you need to make another list
newlist = []
for x in mylist:
     split_results = x.split('@')
     # Now you have a tuple of the results of your split
     # add the second item to the new list
     newlist.append(split_results[1])

Once you understand that well, you can get fancy and use list comprehension:

newlist = [x.split('@')[1] for x in mylist]

Upvotes: 11

dannyxn
dannyxn

Reputation: 422

That's my solution with nested for loops:

myl = ['[email protected]', '[email protected]'...]
results = []
for element in myl:
    for x in element:
        if x == '@':
            x =  element.index('@')
            results.append(element[x+1:])

Upvotes: 0

Related Questions