2

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?

1
  • Welcome to StackOverflow. Please indent code by highlighting it and clicking the { } button. There's never a need to put <br> elements in the post. Either a blank line in between, or two spaces at the end of a line will create a paragraph/line break. Commented Jul 28, 2013 at 21:01

4 Answers 4

13

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Would be fun if * worked on lists so that you could just do ['.'.join(t) for t in strings * tlds] or the like. :-)
@FrerichRaabe, You could write a class that extends list, and implement any operator you like :-)
7

A (nested) list comprehension would be another alternative:

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

Comments

5

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']

3 Comments

@FakeRainBrigand: Neither did you add information nor did you improve readability... Congrats!
I respectfully disagree. Users unfamiliar with iPython would have had a difficult time reading that. But, it's your answer, so I'll rollback the edit if you wish.
Actually you have a point here. The In [x], Out [y] stuff might be confusing to some people. Replacing those by >>> would have been sufficient in my eyes though...
2

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

1 Comment

wow, that is simple, and I understand exactly what it's doing. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.