2

Noob here, Okay so i want to append each integer generated from "range(3,20)" to another similar range "range(22,40)

from itertools import chain

L1 = 3
H1 = 20
L2 = 22
H2 = 40

new_list = [x for x in chain(range(L1,H1))]
new_list2 = [xx for xx in chain(range(L2,H2))]
print (new_list + new_list2)

Results should be:

322
323
324
325...
422
423
424
425...

Current results from above code:

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
1
  • Note: this is not the actual range. It is much bigger, so if someone knows of a more efficient way, please let me know. Commented Sep 25, 2019 at 1:02

2 Answers 2

2

This should work:

L1, H1 = 3, 20
L2, H2 = 22, 40

new_list = [int(str(a) + str(b)) for a in range(L1, H1) for b in range(L2, H2)]
print(new_list)

# [322, 323, ..., 339, 422, 423, ..., 439, 522, ..., 939, 1022, 1023, ..., 1939]

It's a kind of hacky workaround for your kind of hacky use case: for each pair of numbers a and b from your two ranges, we

  1. Convert a and b to strings
  2. Concatenate them (so a=3 and b=22 produces '322')
  3. Convert the result back into an integer
Sign up to request clarification or add additional context in comments.

3 Comments

Okay so i tried the line below since memory will be an issue but still ran into MemoryError. new_list = tuple((int(str(a) + str(b)) for a,b in itertools.product(range(L1, H1), range(L2, H2))))
If your goal is to print out the numbers, rather than store them, then don't do tuple. Just do new_list = (int(str(a) + str(b)) for a in range(L1, H1) for b in range(L2, H2)) - with just the parentheses, and not a tuple(), it produces a generator that doesn't take constant memory. Thereafter you can do a for loop: for n in new_list: print(n)
i'm getting "<generator object <genexpr> at 0x019610B0>" as a result
2

You are talking about the product of two lists, so an itertools solution would look like:

[int(str(a) + str(b)) for a,b in itertools.product(range(L1, H1), range(L2, H2))]

Note that your chain is superfluous and can simply be dropped. Also, if the ranges are large so that memory becomes an issue, you could use the generator expression

(int(str(a) + str(b)) for a,b in itertools.product(range(L1, H1), range(L2, H2)))

since in many ways the point of itertools is to allow for memory-efficient iteration.

Comments

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.