Nizamuddin Shaikh
Nizamuddin Shaikh

Reputation: 420

How do I join elements of tuples of a list through list comprehension

I have a list containing tuples of three elements which contain e-mail data.

email_data = [('jbd', 'email', '.com'), ('my_jbd', 'my_site', '.com')]

What I am trying to attain is to join three elements of each tuple and get email address like '[email protected]' and for that I am using list comprehension as under:

email_list = [  (y+'@', y) [i!=0] for x in result for i, y in enumerate(x) ]
print( email_list ) # ['jbd@', 'email', '.com', 'my_jbd@', 'my_site', '.com']

What I exactly require is list like this -> ['[email protected]', 'my_jbd@my_site.com'].
Since, I am a beginner in Python, I am clueless as to how do I join these tuple elements within list comprehension and get a list containing email data. Please guide me.

Upvotes: 0

Views: 113

Answers (4)

Moses Wynn
Moses Wynn

Reputation: 43

This should work:

[f'{el[0]}@{el[1]}{el[2]}' for el in email_data]

What we are doing here is using a format string to pass in each tuple which we are naming 'el' in the list comprehension.

Upvotes: 1

Roshin Raphel
Roshin Raphel

Reputation: 2689

Try :

email_data = [('jbd', 'email', '.com'), ('my_jbd', 'my_site', '.com')]
for i in email_data :
    s = i[0] + '@'+''.join(i[1:])
    print(s)

Upvotes: 0

Sanket Singh
Sanket Singh

Reputation: 1346

Use:

email_data=[i[0]+"@"+i[1]+i[2] for i in email_data]
print(email_data)

Upvotes: 1

chepner
chepner

Reputation: 530960

Use the format method.

email_list = ["{}@{}{}".format(*t) for t in email_data]

Upvotes: 2

Related Questions