2

I have this array which is working:

urls = [
    'a.com/%s' % page for page in xrange(1,4,1)
]

However, when I tried this, it's not.

urls = [
    'a.com/%s' % page for page in xrange(1,4,1),
    'b.com/%s' % page for page in xrange(1,4,1)
]

The error message is NameError: name 'page' is not defined

How can I generate an array like this in shorthand?

urls = [
    'a.com/1',
    'a.com/2',
    'a.com/3',
    'b.com/1',
    'b.com/2',
    'b.com/3',
]

Update:

Some has suggested that this post is duplicated with this post: How to append list to second list (concatenate lists), however, I disagree.

Even though the solution is the same, however, the purpose of the question is different. Just in case, there are other users wonder how to use multiple xrange in array, then the answer to this question, or the other question could be their best answer.

Community
  • 1
  • 1
Vicheanak
  • 6,444
  • 17
  • 64
  • 98

4 Answers4

2

Just concatenate two lists.

urls = ['a.com/%s' % page for page in xrange(1,4,1)]+['b.com/%s' % page for page in xrange(1,4,1)]
Daneel
  • 1,173
  • 4
  • 15
  • 36
2

You can use a generator (actually list comprehension) statement like the following:

urls = ['{0}.com/{1}'.format(site, page) for site in ['a', 'b'] for page in xrange(1,4,1)]

This results in a single list:

['a.com/1', 'a.com/2', 'a.com/3', 'b.com/1', 'b.com/2', 'b.com/3']
Stephen B
  • 1,246
  • 1
  • 10
  • 23
0

You basically need nested loop. In comprehension it looks like

['{}/{}'.format(host, path) for path in range(4) for host in ('a.com', 'b.com')]
Slam
  • 8,112
  • 1
  • 36
  • 44
0

If you want to generate a list with the same pattern but greater length, you could do like this:

import string

urls = ['%s.com/%s' % (string.ascii_lowercase[i], page + 1) for i in xrange(10) for page in xrange(10)]
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50