Posted on Leave a comment

Python Join List Slice

To join and replace all strings in a list lst between start index 1 and end index 5, use the one-liner lst[1:5] = [''.join(lst[1:5])]. This solution is based on slice assignment that selects the slice you want to replace on the left and the values to replace it on the right side of the assignment.

Problem: Given a list of strings. How to join all strings in a given list slice and replace the slice with the joined string?

Example:You start with the following list:

lst = ['i', 'l', 'o', 'v', 'e', 'u']

You want to join the slice ['l', 'o', 'v', 'e'] with start index 1 and end index 4 (included) and replace it in the list to obtain the result:

# Output: ['i', 'love', 'u']

You can get a quick overview of all three methods in the following interactive Python shell. If you’re short on time—method 1 using slice assignment is the most Pythonic solution!

Exercise: Modify the code so that only elements with start index 2 and end index 4 (included) are replaced by the joined string!

Method 1: Slice Assignment

Slice assignment is a little-used, beautiful Python feature to replace a slice with another sequence. Select the slice you want to replace on the left and the values to replace it on the right side of the equation.

Here’s how you can join and replace all strings in a list slice (between indices 1 and 5) in a single line of Python code:

# Method 1: Slice Assignments
lst = ['i', 'l', 'o', 'v', 'e', 'u']
lst[1:5] = [''.join(lst[1:5])]
print(lst)
# ['i', 'love', 'u']

The one-liner lst[1:5] = [''.join(lst[1:5])] performs the following steps:

  • Select the slice to be replaced on the left-hand side of the equation with lst[1:5]. Read more about slicing on my Finxter blog tutorial.
  • Create a list that replaces this slice on the right-hand side of the equation with [...].
  • Select the slice of string elements to be joined together ('l', 'o', 'v', 'e') with lst[1:5].
  • Pass this slice into the join function to create a new string with all four characters 'love'.
  • This string replaces all four selected positions in the original list.

If you love the power of Python one-liners, check out my new book with the same name “Python One-Liners” on Amazon (published in 2020 with San Francisco’s high-quality NoStarch publishing house).

Method 2: List Concatenation + Slicing + Join

A simpler but quite readable method is to use simple list concatenation. Read more on my Finxter blog tutorial to master all different ways to concatenate lists in Python.

# Method 2: List Concatenation + Join
lst = ['i', 'l', 'o', 'v', 'e', 'u']
lst = lst[:1] + [''.join(lst[1:5])] + lst[5:]
print(lst)
# ['i', 'love', 'u']

This approach uses three slicing calls to select (or create) three lists. Then, it glues them together using the + operator. This approach has the slight disadvantage that a new list is created in memory (rather than working on the old list). Thus, it’s slightly less memory-friendly as the first method.

Method 3: Naive

This method is what a non-Python coder (maybe coming from Java or C++) would use. It’s NOT the recommended way though.

# Method 3: Naive
lst = ['i', 'l', 'o', 'v', 'e', 'u']
new = ''
for i in range(1,5): new += lst[i]
lst = lst[:1] + [new] + lst[5:]
print(lst)
# ['i', 'love', 'u']

Instead of selecting the slice of strings to be joined using slicing, the coder creates a string variable new and adds one character at-a-time. This is very inefficient as many different strings are created—each time one adds one more character to the string.

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!

Posted on Leave a comment

Python Join List Pairs

Given a list of strings. Join the first with the second string, the second with the third, and so on. The one-liner [lst[i] + lst[i+1] for i in range(0, len(lst), 2)] solves the problem by using the range function to iterate over every other index i=0, 2, 4, 5, ... to concatenate the i-th and the i+1-th elements in a list comprehension expression with lst[i] + lst[i+1].

You may already know the normal join function in Python:

Intro: Python Join

Problem: Given a list of elements. How to join the elements by concatenating all elements in the list?

Example: You want to convert list ['learn ', 'python ', 'fast'] to the string 'learn python fast'.

Quick Solution: to convert a list of strings to a string, do the following.

  • Call the ''.join(list) method on the empty string '' that glues together all strings in the list and returns a new string.
  • The string on which you call the join method is used as a delimiter between the list elements.
  • If you don’t need a delimiter, just use the empty string ''.

Code: Let’s have a look at the code.

lst = ['learn ', 'python ', 'fast']
print(''.join(lst))

The output is:

learn python fast

However, what if you want to do something different. Rather than joining all strings in the list to a single string, you want to join the strings in the list in pairs.

Problem: Python Join List Pairs

Problem: Given a list of strings. Join the first with the second string, the second with the third, and so on.

Example: Let’s consider the following minimal example:

['x', 'y', 'v', 'w']

Is there any simple way to pair the first with the second and the third with the fourth string to obtain the following output?

['xy', 'vw']

Note that the length of the strings in the list is variable so the following would be a perfectly acceptable input:

['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff'] 

You can play with all three methods before diving into each of them:

Exercise: What’s the most Pythonic method?

Method 1: Zip() + List Comprehension

You can use the following smart one-liner solution

lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
out = [x + y for x,y in zip(lst[::2], lst[1::2])]
print(out)
# ['aaaab', 'ccdddd', 'eeefff']

The one-liner uses the following strategy:

  • Obtain two slices lst[::2] and lst[1::2] of the original list over every other element starting from the first and the second elements, respectively. If you need to refresh your slicing skills, check out my detailed blog article.
  • Zip the two slices to a sequence of tuples using the zip(...) function. This aligns the first with the second elements from the original list, the third with the forth, and so on. To refresh your zip() skills, check out my blog tutorial here.
  • Use list comprehension to iterate over each pair of values x,y and concatenate them using list concatenation x+y. For a refresher on list comprehension, check out this free tutorial—and for a refresher on list concatenation, check out this one.

Method 2: Iterator + List Comprehension

You can also use an iterator to accomplish this:

lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
it = iter(lst)
out = [x + next(it, '') for x in it] print(out)
# ['aaaab', 'ccdddd', 'eeefff']

Here’s the idea:

  • Create an iterator object it using the built-in function iter().
  • Use list comprehension to go over each element in the iterator.
  • Concatenate each element with the return value of calling the next() function on the iterator. This ensures that the iterator moves one position further iterating over the list. So, the next element x won’t be a duplicate.

Method 3: Use List Comprehension with Indexing

This method is the most straightforward one for Python beginners:

lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
out = [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]
print(out)
# ['aaaab', 'ccdddd', 'eeefff']

The idea is simply to use the range function to iterate over every other index i=0, 2, 4, 5, ... to access the i-th and the i+1-th elements at the same time in the expression statement of list comprehension (to concatenate those with lst[i] + lst[i+1]).

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!

Posted on Leave a comment

Introducing “Web Live Preview”

Avatar

Tim

If you work on any type of app that has a user interface (UI) you probably have experienced that inner-loop development cycle of making a change, compile and run the app, see the change wasn’t what you wanted, stop debugging, then re-run the cycle again. Depending on the frameworks or technology you use, there are options to improve this experience such as edit-and-continue, Xamarin Hot Reload, and design-time editors. Of course, nothing will show the UI of your app like…well, your app!

For ASP.NET WebForms we have had designers for a while allowing you to switch from your WebForms code view to the Design view to get an idea what the UI may look like. As modern UI frameworks have evolved and relied more on fragments or components of CSS/HTML/etc. this design view may not always reflect the UI:

Screenshot of designer and rendered view of HTML

And these frameworks and UI libraries are becoming more popular and common to a web developer’s experience. We ship them in the box as well with some of our Visual Studio templates! As we looked at some of the web trends and talked with customers in our user research labs we wanted to adapt to that philosophy that the best representation of your UI, data, state, etc. is your actual running app. And so that is what we are working on right now.

Starting today you can download our preview Visual Studio extension for a new editing mode we’re calling “web live preview.” The extension is available now so head on over to the Visual Studio Marketplace and download/install the “Web Live Preview” extension for Visual Studio 2019. Seriously, go do that now and just click install, then come back and read the rest. It will be ready for you when you’re done!

Using the extension

After installing the extension, in an ASP.NET web application you’ll now have an option that says “Edit in Browser” when right-clicking on an ASPX page:

Screenshot of context menu

This will launch your default browser with your app in a special mode. You should immediately notice a small difference in that your view has some adorners on it:

Screenshot of adorners on web page

In this mode you can now interactively select elements on this view and see the selection synchronized with your source. Even if you select something that comes from a master page, the synchronization will open that page in Visual Studio to navigate to the selection.

Animation of element selection

So what you may say, well it’s not just selection synchronization, but source as well. You may have a web control and be selecting those elements and we know that, for example, that is an asp:DataGrid component. As you make changes to the source as well, they are immediately reflected in the running app. Notice no saving or no browser refresh happening:

Animation of changing styles

When working with things like Razor pages, we can detect code as well and even interact within those blocks of code. Here in a Razor page I have a loop. Notice how the selection is identified as a code loop, but I can still make some modifications in the code and see it reflected in the running app:

Animation of changing code

So even in your code blocks within your HTML you can make edits and see them reflected in your running app, shortening that inner loop to smaller changes in your process.

But wait, there’s more!

If you already use browser developer tools you may be asking if this is a full replacement for that for you. And it probably is NOT and that is by design! We know web devs rely a lot on developer tools in browsers and we are experimenting as well with a little extension (for Edge/Chrome) that synchronizes in the rendered dev tools view as well. So now you have synchronization across source representation (including controls/code/static) to rendered app, and with dev tools DOM tree views…and both ways:

Animation of browser tools integration

We have a lot more to do, hence this being a preview of our work so far.

Current constraints

With any preview there are going to be constraints, so here they are for the time of this writing. We eventually see this just being functionality for web developers in Visual Studio without installing anything else, so the extension is temporary. For now, we support the .NET Framework web project types for WebForms and MVC. Yes, we know, we know you want .NET Core and Blazor support. This is definitely on our roadmap, but we wanted to tackle some very known scenarios where our WebForms customers have been using design view for a while. We hear you and this has been echoed in our research as well…we are working on it!

For pure code changes outside of the ASPX/Razor pages we don’t have a full ‘hot reload’ story yet so you will have to refresh the browser in those cases where some fundamental object models are changing that you may rely on (new classes/functions/properties, changed data types, etc.). This is something that we hope to tackle more broadly for the .NET ecosystem and take all that we have learned from customers using similar experiments we have had in this area.

The extension works with Chromium-based browsers such as the latest Microsoft Edge and Google Chrome browsers. This also enables us to have a single browser developer tools extension that handles that integration as well. To use that browser extension, you will have to use developer mode in your browser and load the extension from disk. This process is fairly simple but you have to follow a few steps which are documented on adding and removing extensions in Edge. The location of the dev tools plugin is located at C:\Program Files (x86)\Microsoft Visual Studio\2019\Common7\IDE\Extensions\Microsoft\Web Live Preview\BrowserExtension (assuming you have the default Visual Studio 2019 install location and ensuring you specify Community/Professional/Enterprise you have installed). Please note this is also a temporary solution as we are in development of these capabilities. Any final browser tools extensions would be distributed in browser stores.

Summary

If you are one of our customers that can leverage this preview extension we’d love for you to download and install it and give it a try. If you have feedback or issues, please use the Visual Studio Feedback mechanism as that helps us get diagnostic information for any issues you may be facing. We know that you have a lot of tools at your disposal but we hope this web live preview mode will make some of your flow easier. Nothing to install into your project, no tool-specific code in your source, and (eventually) no additional tools to install. Please give it a try and let us know what you think!

On behalf of the team working on web tools for you, thank you for reading!

Posted on Leave a comment

DragonRuby Game Framework

DragonRuby is a game development framework powered by the Ruby programming language.  It is lightweight and crossplatform with an easy to learn API.  It is regularly $47USD, however it is currently included in the Bundle For Racial Justice currently running on Itch.io, along with hundreds of games for just $5.

Key features of DragonRuby include:

  • Dirt simple apis capable of creating complex 2D games.
  • Fast as hell. Powered by highly optimized C code written by Ryan C. Gordon, the creator of SDL (a library that powers every commercial game engine in the world).
  • Battle tested by Amir Rajan, a critically acclaimed indie game dev.
  • Tiny. Like really tiny. The entire engine is a few megabytes.
  • Hot loaded, realtime coding, optimized to provide constant feedback to the dev. Productive and an absolute joy to use.
  • Turn key builds for Windows, MacOS, and Linux with seamless publishing to Itch.io.
  • Cross platform: PC, Mac, Linux, iOS, Android, Nintendo Switch, XBOX One, and PS4 (mobile and console compilation requires a business entity, NDA verification, and a Professional GTK License, contact us).

You can learn more about DragonRuby in the video below.

GameDev News Programming


Posted on Leave a comment

How to Merge Lists into a List of Tuples? [6 Pythonic Ways]

Merge Lists to List of Tuples

The most Pythonic way to merge multiple lists l0, l1, ..., ln into a list of tuples (grouping together the i-th elements) is to use the zip() function zip(l0, l1, ..., ln). If you store your lists in a list of lists lst, write zip(*lst) to unpack all inner lists into the zip function.

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l = list(zip(l1, l2))
print(l)
# [(1, 4), (2, 5), (3, 6)]

The proficient use of Python’s built-in data structures is an integral part of your Python education. This tutorial shows you how you can merge multiple lists into the “column” representation—a list of tuples. By studying these six different ways, you’ll not only understand how to solve this particular problem, you’ll also become a better coder overall.

Problem: Given a number of lists l1, l2, …, ln. How to merge them into a list of tuples (column-wise)?

Example: Say, you want to merge the following lists

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99]

into a list of tuples

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

This tutorial shows you different ways to merge multiple lists into a list of tuples in Python 3. You can get a quick overview in our interactive Python shell:

Exercise: Which method needs the least number of characters?

Method 1: Zip Function

The most Pythonic way that merges multiple lists into a list of tuples is the zip function. It accomplishes this in a single line of code—while being readable, concise, and efficient.

The zip() function takes one or more iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)].

Here’s the code solution:

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] print(list(zip(l0, l1, l2)))

The output is the following list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

Note that the return value of the zip() function is a zip object. You need to convert it to a list using the list(...) constructor to create a list of tuples.

If you have stored the input lists in a single list of lists, the following method is best for you!

Method 2: Zip Function with Unpacking

You can use the asterisk operator *lst to unpack all inner elements from a given list lst. Especially if you want to merge many different lists, this can significantly reduce the length of your code. Instead of writing zip(lst[0], lst[1], ..., lst[n]), simplify to zip(*lst) to unpack all inner lists into the zip function and accomplish the same thing!

lst = [[0, 'Alice', 4500.00], [1, 'Bob', 6666.66], [2, 'Liz', 9999.99]]
print(list(zip(*lst)))

This generates the list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

I’d consider using the zip() function with unpacking the most Pythonic way to merge multiple lists into a list of tuples.

Method 3: List Comprehension

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

The example [x for x in range(3)] creates the list [0, 1, 2].

Related Article: You can read more about list comprehension in my ultimate guide on this blog.

You can use a straightforward list comprehension statement [(l0[i], l1[i], l2[i]) for i in range(len(l0))] to merge multiple lists into a list of tuples:

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] print([(l0[i], l1[i], l2[i]) for i in range(len(l0))])

The output produces the merged list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

This method is short and efficient. It may not be too readable for you if you’re a beginner coder—but advanced coders usually have no problems understanding this one-liner. If you love to learn everything there is about one-liner Python code snippets, check out my new book “Python One-Liners” (published with San Francisco Publisher NoStarch in 2020).

Method 4: Simple Loop

Sure, you can skip all the fancy Python and just use a simple loop as well! Here’s how this works:

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = []
for i in range(len(l0)): lst.append((l0[i], l1[i], l2[i]))
print(lst)

The output is the merged list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

Especially coders who come to Python from another programming language such as Go, C++, or Java like this approach. They’re used to writing loops and they can quickly grasp what’s going on in this code snippet.

You can visualize the execution of this code snippet in the interactive widget:

Exercise: Click “Next” to see how the memory usage unfolds when running the code.

Method 5: Enumerate

The enumerate() method is considered to be better Python style in many scenarios—for example, if you want to iterate over all indices of a list. In my opinion, it’s slightly better than using range(len(l)). Here’s how you can use enumerate() in your code to merge multiple lists into a single list of tuples:

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = []
for i,x in enumerate(l0): lst.append((x,l1[i],l2[i]))
print(lst)

The output is the list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

Still not satisfied? Let’s have a look at functional programming.

Method 6: Map + Lambda

With Python’s map() function, you can apply a specific function to each element of an iterable. It takes two arguments:

  • Function: In most cases, this is a lambda function you define on the fly. This is the function which you are going to apply to each element of an…
  • Iterable: This is an iterable that you convert into a new iterable where each element is the result of the applied map() function.

The result is a map object. What many coders don’t know is that the map() function also allows multiple iterables. In this case, the lambda function takes multiple arguments—one for each iterable. It then creates an iterable of tuples and returns this as a result.

Here’s how you can create a list of tuples from a few given lists:

l0 = [0, 'Alice', 4500.00]
l1 = [1, 'Bob', 6666.66]
l2 = [2, 'Liz', 9999.99] lst = list(map(lambda x, y, z: (x, y, z), l0, l1, l2))
print(lst)

The output is the merged list of tuples:

[(0, 1, 2), ('Alice', 'Bob', 'Liz'), (4500.0, 6666.66, 9999.99)]

This is both an efficient and readable way to merge multiple lists into a list of tuples. The fact that it isn’t well-known to use the map() function with multiple arguments doesn’t make this less beautiful.

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!

Posted on Leave a comment

ASP.NET Core updates in .NET 5 Preview 5

Avatar

Sourabh

.NET 5 Preview 5 is now available and is ready for evaluation! .NET 5 will be a current release.

Get started

To get started with ASP.NET Core in .NET 5.0 Preview5 install the .NET 5.0 SDK.

If you’re on Windows using Visual Studio, we recommend installing the latest preview of Visual Studio 2019 16.7.

If you’re on macOS, we recommend installing the latest preview of Visual Studio 2019 for Mac 8.7.

Upgrade an existing project

To upgrade an existing ASP.NET Core 5.0 preview4 app to ASP.NET Core 5.0 preview5:

  • Update all Microsoft.AspNetCore.* package references to 5.0.0-preview.5.*.
  • Update all Microsoft.Extensions.* package references to 5.0.0-preview.5.*.

See the full list of breaking changes in ASP.NET Core 5.0.

That’s it! You should now be all set to use .NET 5 Preview 5.

What’s new?

Reloadable endpoints via configuration for Kestrel

Kestrel now has the ability to observe changes to configuration passed to KestrelServerOptions.Configure and unbind from existing endpoints and bind to new endpoints without requiring you to restart your application.

See the release notes for additional details and known issues.

Give feedback

We hope you enjoy this release of ASP.NET Core in .NET 5! We are eager to hear about your experiences with this latest .NET 5 release. Let us know what you think by filing issues on GitHub.

Thanks for trying out ASP.NET Core!

Posted on Leave a comment

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:

  1. You don’t know how to concatenate two range() iterables, or
  2. 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?

Python Join List Range

Concatenate Two range() Iterables

Problem: How to create a new list by concatenating two range() iterables?

Example: You want to concatenate the following two range() iterables

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 list(range(...)) function calls.
  • 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]

There are other ways to concatenate lists—and a more efficient one is to use the itertools.chain() function.

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:

range(10)

You want the following string:

'0123456789'

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 TypeError:

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'

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!

Posted on Leave a comment

Gravity Embeddable Programming Language

Currently trending on Hacker News, Gravity is an open source programming language that is designed to be embedded in iOS and Android applications.  Released under the MIT license, Gravity is entirely C99 code with the single dependency being the C Standard Library, making Gravity incredible portable.  It is also extremely light weight while still being feature rich, with a syntax inspired by the Swift programming language.

Details from the Gravity website:

Gravity is a powerful, dynamically typed, lightweight, embeddable programming language written in C without any external dependencies (except for stdlib). It is a class-based concurrent scripting language with a modern Swift like syntax.

Gravity supports procedural programming, object-oriented programming, functional programming and data-driven programming. Thanks to special built-in methods, it can also be used as a prototype-based programming language.

Gravity has been developed from scratch for the Creo project in order to offer an easy way to write portable code for the iOS and Android platforms. It is written in portable C code that can be compiled on any platform using a C99 compiler. The VM code is about 4K lines long, the multipass compiler code is about 7K lines and the shared code is about 3K lines long. The compiler and virtual machine combined, add less than 200KB to the executable on a 64 bit system.

The source code for Gravity is available here, with various editor syntax support available for download here.  Gravity was ultimately created to be the scripting language behind the Creo IDE for iOS and Mac development.  You can learn more about Gravity in the video below.

GameDev News Programming


Posted on Leave a comment

The Most Pythonic Way to Join a List in Reverse Order

The most efficient method to join a list of Python strings in reverse order is to use the Python code ''.join(l[::-1]). First, reverse the list l using slicing with a negative step size l[::-1]. Second, glue together the strings in the list using the join(...) method on the empty string ''.

Problem: Given a list of strings. How to join the strings in reverse order?

Example: You want to join the following list

l = ['n', 'o', 'h', 't', 'y', 'p']

to obtain the joined string in reverse order

python

Let’s get a short overview on how to accomplish this.

Solution Overview: You can try the three methods in our interactive Python shell.

Next, we’ll dive into each method separately.

Method 1: Join + Slicing

The first and most Pythonic method to reverse and join a list of strings is to use slicing with a negative step size.

You can slice any list in Python using the notation list[start:stop:step] to create a sublist starting with index start, ending right before index stop, and using the given step size—which can also be negative to slice from right to left. If you need a refresher on slicing, check out our detailed Finxter blog tutorial or our focused book “Coffee Break Python Slicing”.

Here’s the first method to reverse a list of strings and join the elements together:

l = ['n', 'o', 'h', 't', 'y', 'p'] # Method 1
print(''.join(l[::-1]))
# python

The string.join(iterable) method joins the string elements in the iterable to a new string by using the string on which it is called as a delimiter.

You can call this method on each list object in Python. Here’s the syntax:

string.join(iterable)

Argument Description
iterable The elements to be concatenated.

Related articles:

Method 2: Join + reversed()

The second method is also quite Pythonic: using the reversed() built-in function rather than slicing with a negative step size. I’d say that beginners generally prefer this method because it’s more readable to them—while expert coders prefer slicing because it’s more concise and slightly more efficient.

l = ['n', 'o', 'h', 't', 'y', 'p']
print(''.join(reversed(l)))
# python

The join method glues together all strings in the list—in reversed order!

Method 3: Simple Loop

The third method is the least Pythonic one: using a loop where it’s not really needed. Anyways, especially coders coming from other programming languages like Java or C++ will often use this approach.

l = ['n', 'o', 'h', 't', 'y', 'p'] s = ''
for x in reversed(l): s += x
print(s)
# python

However, there are several disadvantages. Can you see them?

  • The code is less concise.
  • The code is less efficient because of the repeated string concatenation. Each loop execution causes the creation of a new string, which is highly inefficient.
  • The code requires the definition of two new variables x and s and introduces a higher level of complexity.

You can see this in our interactive memory visualizer:

Exercise: click “Next” to see the memory objects used in this code snippet!

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!

Posted on Leave a comment

How to Combine Two Python Lists and Remove Duplicates in Second List?

Problem: Given two lists [1, 2, 2, 4] and [2, 5, 5, 5, 6]. How do you combine those lists to the new list [1, 2, 2, 4, 5, 6] by removing the duplicates in the second list?

Note: You want to remove all duplicates in the second list and the elements in the second list that are already in the first list.

Solution: Use the following three steps to combine two lists and remove the duplicates in the second list:

  • Convert the first and second lists to a set using the set(...) constructor.
  • Use the set minus operation to get all elements that are in the second list but not in the first list.
  • Create a new list by concatenating those elements to the first list.

Here’s the code:

# Create the two lists
l1 = [1, 2, 2, 4]
l2 = [2, 5, 5, 5, 6] # Find elements that are in second but not in first
new = set(l2) - set(l1) # Create the new list using list concatenation
l = l1 + list(new)
print(l)
# [1, 2, 2, 4, 5, 6]

Try it yourself in our interactive Python shell:

Exercise: Can you rewrite this in a single line of Python code (Python One-Liner)?

Let’s dive into the more concise one-liner to accomplish the same thing:

l = l1 + list(set(l2) - set(l1))

If you want to learn about the most Pythonic way to remove ALL duplicates from a Python list, read on:

How to Remove Duplicates From a Python List?

Naive Method: Go over each element and check whether this element already exists in the list. If so, remove it. However, this takes a few lines of code.

Efficient Method: A shorter and more concise way is to create a dictionary out of the elements in the list to remove all duplicates and convert the dictionary back to a list. This preserves the order of the original list elements.

lst = ['Alice', 'Bob', 'Bob', 1, 1, 1, 2, 3, 3]
print(list(dict.fromkeys(lst)))
# ['Alice', 'Bob', 1, 2, 3]
  1. Convert the list to a dictionary with dict.fromkeys(lst).
  2. Convert the dictionary into a list with list(dict).

Each list element becomes a new key to the dictionary. For example, the list [1, 2, 3] becomes the dictionary {1:None, 2:None, 3:None}. All elements that occur multiple times will be assigned to the same key. Thus, the dictionary contains only unique keys—there cannot be multiple equal keys.

As dictionary values, you take dummy values (per default).

Then, you convert the dictionary back to a list, throwing away the dummy values.

Here’s the code:

>>> lst = [1, 1, 1, 3, 2, 5, 5, 2]
>>> dic = dict.fromkeys(lst)
>>> dic
{1: None, 3: None, 2: None, 5: None}
>>> duplicate_free = list(dic)
>>> duplicate_free
[1, 3, 2, 5]

Related blog 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!