Does range function allows concatenation ? Like i want to make a range(30)
& concatenate it with range(2000, 5002)
. So my concatenated range will be 0, 1, 2, ... 29, 2000, 2001, ... 5001
Code like this does not work on my latest python (ver: 3.3.0)
range(30) + range(2000, 5002)
You can use
itertools.chain
for this:It works for arbitrary iterables. Note that there's a difference in behavior of
range()
between Python 2 and 3 that you should know about: in Python 2range
returns a list, and in Python3 an iterator, which is memory-efficient, but not always desirable.Lists can be concatenated with
+
, iterators cannot.I know this is a bit old thread, but for me, the following works.
So does this
Of course the print output is different in the 2nd from the 1st.
Edit: I missed the follow-up comment form the OP stating python 3. This is in my python 2 environment.
Can be done using list-comprehension.
Works for your request, but it is a long answer so I will not post it here.
note: can be made into a generator for increased performance:
or even into a generator variable.
range()
in Python 2.x returns a list:xrange()
in Python 2.x returns an iterator:And in Python 3
range()
also returns an iterator:So it is clear that you can not concatenate iterators other by using
chain()
as the other guy pointed out.I like the most simple solutions that are possible (including efficiency). It is not always clear whether the solution is such. Anyway, the
range()
in Python 3 is a generator. You can wrap it to any construct that does iteration. Thelist()
is capable of construction of a list value from any iterable. The+
operator for lists does concatenation. I am using smaller values in the example:This is what
range(5) + range(10, 20)
exactly did in Python 2.5 -- becauserange()
returned a list.In Python 3, it is only useful if you really want to construct the list. Otherwise, I recommend the Lev Levitsky's solution with itertools.chain. The documentation also shows the very straightforward implementation:
The solution by Inbar Rose is fine and functionally equivalent. Anyway, my +1 goes to Lev Levitsky and to his argument about using the standard libraries. From The Zen of Python...
In my opinion, the
itertools.chain
is more readable. But what really is important...... it is about 3 times faster.
With the help of the extend method, we can concatenate two lists.