![]() |
|
[Tut] Python Join List Range: A Helpful Guide - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Join List Range: A Helpful Guide (/thread-95641.html) |
[Tut] Python Join List Range: A Helpful Guide - xSicKxBot - 06-12-2020 Python Join List Range: A Helpful Guide If the search phrase “Python Join List Range” brought you here, you’re having most likely one of the following problems:
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 thePython programming language. But let’s first play with some code and get an overview of the two solutions, shall we? https://trinket.io/embed/python/e36ce7dbd8 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 Code: range()Example: You want to concatenate the following two Code: range()Code: range(1,5) + range(5,10)Your expected result is: Code: [1, 2, 3, 4, 5, 6, 7, 8, 9]Developing the Solution: The result of the Code: range(start, stop, step)Code: >>> range(10)
range(0, 10)
>>> type(range(10))
<class 'range'>Unfortunately, you cannot simply concatenate two range objects because this would cause a Code: TypeErrorCode: >>> 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.
Code: l = list(range(1, 5)) + list(range(5, 10))
print(l)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]There are other ways to concatenate lists—and a more efficient one is to use the Code: itertools.chain()Code: 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 concatenateit to another list object. By avoiding the superfluous list creation, you win in performance(at the costs of adding another libraryto your code). You can see how the first version creates multiple list objects in memory in the interactive memory visualizer: https://pythontutor.com/iframe-embed.html#code=l1%20%3D%20list%28range%281,%205%29%29%20%0Al2%20%3D%20list%28range%285,%2010%29%29%0Al%20%3D%20l1%20%2B%20l2%0Aprint%28l%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=3&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false 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: Code: range(10)You want the following string: Code: '0123456789'Solution: To convert a range object to a string, use the Code: string.join()Code: str(x) for x in range(...)Code: TypeErrorCode: 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 Code: str(x) for x in range(...)Code: join(...)Code: print(''.join(str(x) for x in range(10))) '0123456789'You can use different delimiterstrings if you need to: Code: print('-'.join(str(x) for x in range(10))) '0-1-2-3-4-5-6-7-8-9'Related articles:
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. Join the free webinar now! |