If the search phrase “Python Join List Range” brought you here, you’re having most likely one of the following problems:
- You don’t know how to concatenate two
- You want to use
.join()to create a string from a
range()iterable—but it doesn’t work.
In any case, by reading this article, I hope that you’ll not only answer your question, you’re also become a slightly better (Python) coder by understanding important nuances in the Python programming language.
But let’s first play with some code and get an overview of the two solutions, shall we?
Exercise: Can you accomplish both objectives in a single line of Python code?
Concatenate Two range() Iterables
Problem: How to create a new list by concatenating two
Example: You want to concatenate the following two
range(1,5) + range(5,10)
Your expected result is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Developing the Solution: The result of the
range(start, stop, step) function is an iterable “range” object:
>>> range(10) range(0, 10) >>> type(range(10)) <class 'range'>
Unfortunately, you cannot simply concatenate two range objects because this would cause a
TypeError—the + operator is not defined on two range objects:
>>> range(1, 5) + range(5, 10) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> range(1, 5) + range(5, 10) TypeError: unsupported operand type(s) for +: 'range' and 'range'
Thus, the easiest way to concatenate two range objects is to do the following.
- Convert both range objects to lists using the
- Use the list concatenation operator
+on the resulting objects.
l = list(range(1, 5)) + list(range(5, 10)) print(l) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
from itertools import chain l = chain(range(1, 5), range(5, 10)) print(list(l)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
This has the advantage that you work purely on iterables rather than lists. There’s no need to waste computational cycles to create a list object if you need it only to concatenate it to another list object. By avoiding the superfluous list creation, you win in performance (at the costs of adding another library to your code).
You can see how the first version creates multiple list objects in memory in the interactive memory visualizer:
Exercise: How many list objects are there in memory after the code terminates?
Use .join() to Create a String From a range() Iterable
Problem: Given a range object—which is an iterable of integers—how to join all integers into a new string variable?
Example: You have the following range object:
You want the following string:
Solution: To convert a range object to a string, use the
string.join() method and pass the generator expression
str(x) for x in range(...) to convert each integer to a string value first. This is necessary as the join function expects an iterable of strings and not integers. If you miss this second step, Python will throw a
print(''.join(range(10))) ''' Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> print(''.join(range(10))) TypeError: sequence item 0: expected str instance, int found '''
So, the correct way is to convert each element to a string using the generator expression
str(x) for x in range(...) inside the
join(...) argument list. Here’s the correct code that joins together all integers in a range object in the most Pyhtonic way:
print(''.join(str(x) for x in range(10))) '0123456789'
You can use different delimiter strings if you need to:
print('-'.join(str(x) for x in range(10))) '0-1-2-3-4-5-6-7-8-9'
- Python Lists [Ultimate Guide]
- Python Join [Ultimate Guide]
- Python Generator Expressions and List Comprehension
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.