user2628294
user2628294

Reputation: 33

concatenate all items from two lists in Python

I want to produce a list of possible websites from two lists:

strings = ["string1", "string2", "string3"]
tlds = ["com', "net", "org"]

to produce the following output:

string1.com  
string1.net  
string1.org  
string2.com  
string2.net  
string2.org 

I've got to this:

for i in strings:
    print i + tlds[0:]

But I can't concatenate str and list objects. How can I join these?

Upvotes: 2

Views: 917

Answers (4)

jarmod
jarmod

Reputation: 78573

One very simple way to write this is the same as in most other languages.

for s in strings:
    for t in tlds:
        print s + '.' + t

Upvotes: 2

Frerich Raabe
Frerich Raabe

Reputation: 94289

A (nested) list comprehension would be another alternative:

[s + '.' + tld for s in strings for tld in tlds]

Upvotes: 7

sjakobi
sjakobi

Reputation: 3606

The itertools module provides a function that does this.

from itertools import product
urls = [".".join(elem) for elem in product(strings, tlds)]

The urls variable now holds this list:

['string1.com',
 'string1.net',
 'string1.org',
 'string2.com',
 'string2.net',
 'string2.org',
 'string3.com',
 'string3.net',
 'string3.org']

Upvotes: 5

llb
llb

Reputation: 1741

itertools.product is designed for this purpose.

url_tuples = itertools.product(strings, tlds)
urls = ['.'.join(url_tuple) for url_tuple in url_tuples]
print(urls)

Upvotes: 13

Related Questions