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.
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.
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:
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.
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!
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.
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:
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.
Convert the list to a dictionary with dict.fromkeys(lst).
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.
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.
Notice how the first and the last dictionaries carry the same key 'a'.
How do you merge all those dictionaries into a single dictionary to obtain the following one?
{'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
Notice how the value of the duplicate key 'a' is the value of the last and not the first dict in the list of dicts.
To merge multiple dictionaries, the most Pythonic way is to use dictionary comprehension {k:v for x in l for k,v in x.items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.
Let’s explore all the available options in the remaining article:
Exercise: Run the code—which method generates a different output than all the other methods?
Method 1: Dictionary Comprehension With Nested Context
You can use dictionary comprehension {k:v for x in l for k,v in x.items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.
Create a new dictionary using the {...} notation.
Go over all dictionaries in the list of dictionaries l by using the outer loop for x in l.
Go over all (key, value) pairs in the current dictionary x by using the x.items() method that returns an iterable of (key, value) pairs.
Fill the new dictionary with (key, value) pairs k:v using the general dictionary comprehension syntax {k:v for ...}.
l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}] d = {k:v for x in l for k,v in x.items()}
print(d)
# {'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
This is the most Pythonic way to merge multiple dictionaries into a single one and it works for an arbitrary number of dictionaries.
Method 2: Simple Nested Loop
Use a simple nested loop to add each (key, value) pair separately to a newly created dictionary:
Create a new, empty dictionary.
Go over each dictionary in the list of dictionaries.
Go over each (key, value) pair in the current dictionary.
Add the (key, value) pair to the new dictionary—possibly overwriting “older” keys with the current one.
l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}] d = {}
for dictionary in l: for k, v in dictionary.items(): d[k] = v print(d)
{'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
You can visualize the execution flow of this code here:
This is the easiest to read for many beginner coders—but it’s much less concise and less Pythonic.
Method 3: Use the update() Method
The dict.update(x) method updates the dictionary on which it is called with a bunch of new (key, value) pairs given in the dictionary argument x. The method to merge multiple dictionaries is simple:
Create a new, empty dictionary.
Go over each dictionary in the list of dictionaries.
Update the new dictionary with the values in the current dictionary.
l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}] d = {}
for dictionary in l: d.update(dictionary) print(d)
# {'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
This is a very readable and efficient way and it’s shorter than method 2.
Method 4: Dictionary Unpacking
When applied to a dictionary d, the double asterisk operator **d unpacks all elements in d into the outer dictionary. You can only use this “dictionary unpacking” method within an environment (in our case a dictionary) that’s capable of handling the (key, value) pairs.
This is a concise, efficient, and Pythonic way to merge multiple dictionaries. However, it’s not optimal because you must manually type each unpacking operation. If the dictionary has 100 elements, this wouldn’t be feasible.
Note: you cannot use dictionary unpacking in dictionary comprehension to alleviate this problem—Python will throw a SyntaxError!
Method 5: Use ChainMap With Unpacking
If you’re not happy with either of those methods, you can also use the ChainMap data structure from the collections library.
However, this does not exactly meet our specifications: the fifth dictionary in our collection does not overwrite the (key, value) pairs of the first dictionary. Other than that, it’s a fast way to merge multiple dictionaries and I wanted to include it here for comprehensibility.
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.
When teaching the Finxter Python students, I’m often shocked how even intermediate-level coders do not understand the very basic foundations of computer science. In CS, there’s almost nothing as fundamental as a simple, plain byte. (You know, that sequence of 0s and 1s called bits).
This tutorial aims to clarify some misconceptions and questions regarding Bytes in Python—a term that has a quite different meaning to bytes in general. In particular, you’ll learn the definition of the Byte object and how to correctly join a sequence of Bytes. Here’s the short answer:
A Python Byte is a sequence of bytes. You create a Byte object using the notation b'...' similar to the string notation '...'. To join a list of Bytes, call the Byte.join(list) method. If you try to join a list of Bytes on a string delimiter, Python will throw a TypeError, so make sure to call it on a Byte object b' '.join(...) rather than ' '.join(...).
Before you dive into all of this in a step-by-step manner, let’s play a bit with the interactive code shell to open your knowledge gap:
Exercise: What happens if you join the list of Bytes on a string delimiter? Try it in the shell!
What’s a Byte in Python Anyway?
You think you know what a byte is, right? It’s a sequence of 8 bits.
Well, that’s what a byte is outside the Python world. In Python, it’s not the whole story.
Python comes with a built-in Byte data type. According to the official documentation, the Byte object is an “immutable sequence of bytes“. If you talk about a byte outside Python, you mean 8 bits. If you talk about a byte inside Python, you mean a sequence of one or more bytes.
Let’s keep that on a hold for a moment and look how you create a simple byte object:
>>> a = b'X'
>>> a
b'X'
>>> type(a)
<class 'bytes'>
You create the Byte object just like you create a string in Python using the single, double, or triple quotes around a text that’s to be encoded in a “sequence of bytes”. In this case, the sequence of bytes consists only of the bytes needed to encode a single character 'X'. The ASCII code of character 'X' is 88, or in binary format 0b1011000. You can see that you only need one byte to encode the character.
But can you also create more complicated “Python Byte” objects that consist of more “real bytes”? Sure, you can:
>>> a = b'hello'
>>> a
b'hello'
>>> type(a)
<class 'bytes'>
Again, you create the Byte object for 'hello'. You cannot encode the whole string 'hello' in eight bits (=byte), so the Python Byte object a now consists of a “sequence of bytes”.
Takeaway: A (Python) Byte is a sequence of bytes and you can use it just like you use strings by using the syntax b'...' instead of '...'. As string objects, Bytes are immutable—so you cannot modify them after creation.
Concatenate Byte Strings in Python
You can concatenate two byte objects x and y in Python by using the (overloaded) add operation x+y:
>>> x = b'hello '
>>> y = b'world!'
>>> x + y
b'hello world!'
This works for Python 2 and Python 3—and it will probably also work in Python 4! (Why? Because the semantics of the __add__ operation won’t change just by setting up a new programming language or modifying an old one.)
How to Join a List of Bytes?
Python Bytes are similar than Python strings (at least for you, the person who used the Byte data structure in their program).
So, joining a list of Bytes is similar than joining a list of strings: use the join method! The Byte object comes with a method Byte.join(iterable) that concatenates all Byte objects in the iterable.
Keep in mind that a Byte object is a sequence of bytes by itself (and not a sequence of bits as you may have expected). And, yes, I’ll repeat this until it sticks.
Syntax: Byte.join(iterable)
Argument
Description
iterable
A collection of Byte objects.
Examples: Let’s see a bunch of examples on how you can join a collection of Byte objects!
lst = [b'Python', b'is', b'beautiful'] # Example 1
print(b' '.join(lst))
b'Python is beautiful' # Example 2
print(b'-'.join(lst))
b'Python-is-beautiful' # Example 3
print(b'\n'.join(lst))
b'Python\nis\nbeautiful'
You get the point: you call the join() method on the Byte object and pass an iterable of Byte objects to be concatenated. Notice how all involved data types are Byte objects!
How to Fix “TypeError: sequence item 0: expected str instance, bytes found”?
A common mistake of many Python coders is to call the wrong join() method! Say, you’ve got an iterable of Bytes to be joined. If you call the string.join(...) method instead of the Byte.join(...) method, Python will throw a TypeError with the following error message:
The error message doesn’t directly tell you how to fix this issue. The reason is that you call the join() method on the string object. And the string join() method expects you to pass an iterable of string objects to be concatenated. But you pass an iterable of Byte objects!
To fix it, simply call the join(...) method on the Byte object b' '.join(...) instead of ' '.join(...).
lst = [b'Python', b'is', b'beautiful']
print(b' '.join(lst))
b'Python is beautiful'
This way, you can easily concatenate multiple Byte objects by using the Byte.join() method.
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.
To intersect multiple sets, stored in a list l, use the Python one-liner l.pop().intersection(*l) that takes the first set from the list, calls the intersection() method on it, and passes the remaining sets as arguments by unpacking them from the list.
So, let’s dive into the formal problem formulation, shall we?
Problem: Given a list or a collection of sets. How to join those sets using the intersection operation?
Example: You’ve got a list of sets [{1, 2, 3}, {1, 4}, {2, 3, 5}] and you want to calculate the intersection {1}.
Solution: To intersect a list of sets, use the following strategy:
Get the first element from the list as a starting point. This assumes the list has at least one element.
Call the intersection() method on the first set object.
Pass all sets as arguments into the intersection() method by unpacking the list with the asterisk operator*list.
The result of the intersection() method is a new set containing all elements that are in all of the sets.
Code: Here’s the one-liner code that intersects a collection of sets.
# Create the list of sets
lst = [{1, 2, 3}, {1, 4}, {1, 2, 3}] # One-Liner to intersect a list of sets
print(lst[0].intersection(*lst))
The output of this code is the intersection of the three sets {1, 2, 3}, {1, 4}, and {2, 3, 5}. Only one element appears in all three sets:
{1}
If you love Python one-liners, check out my new book “Python One-Liners” (Amazon Link) that teaches you a thorough understanding of all single lines of Python code.
Try it yourself: Here’s the code in an interactive code shell that runs it in your browser:
Exercise: Change the code to calculate the union of the sets in the list!
Related video: A similar problem is to perform the union operation on a list of sets. In the following video, you can watch me explain how to union multiple sets in Python:
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.
The most Pythonic way to convert a list of tuples to a string is to use the built-in method str(...). If you want to customize the delimiter string, the most Pythonic way is to concatenate the join() method and the map() function '\n'.join(map(str, lst)) to convert all tuples to strings and gluing those together with the new-line delimiter '\n'.
Exercise: Run the interactive code snippet. Which method do you like most?
Method 1: Default String Conversion
Say, you’ve got a list of tuples, and you want to convert it to a string (e.g., see this SO post). The easiest way to accomplish this is to use the default string conversion method str(...).
The map() function transforms each tuple into a string value, and the join() method transforms the collection of strings to a single string—using the given delimiter '--'. If you forget to transform each tuple into a string with the map() function, you’ll get a TypeError because the join() method expects a collection of strings.
Method 3: Flatten List of Tuples
If you want to flatten the list and integrate all tuple elements into a single large collection of elements, you can use a simple list comprehension statement [str(x) for t in lst for x in t].
lst = [(1,1), (2,1), (4,2)] print('\n'.join([str(x) for t in lst for x in t])) '''
1
1
2
1
4
2 '''
If you want to redefine how to print each tuple—for example, separating all tuple values by a single whitespace character—use the following method based on a combination of the join() method and the map() function with a custom lambda function lambda x: str(x[0]) + ' ' + str(x[1]) to be applied to each list element.
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.
Problem: Given a list of Boolean elements. What’s the best way to join all elements using the logical “OR” and logical “AND” operations?
Example: Convert the list [True, True, False] using
The logical “AND” operation to True and True and False = False,
The logical “OR” operation to True or True or False = True, and
The logical “NOT” operation to [not True, not True, not False] = [False, False, True].
Solution:
To perform logical “AND”, use the built-in Python function all(),
To perform logical “OR”, use the built-in Python function any(), and
To perform logical “NOT”, use a list comprehension statement [not x for x in list].
Here’s the solution for our three examples:
lst = [True, True, False] # Logical "AND"
print(all(lst))
# False # Logical "OR"
print(any(lst))
# True # Logical "NOT"
print([not x for x in lst])
# [False, False, True]
This way, you can combine an arbitrary iterable of Booleans into a single Boolean value.
Puzzle: Guess the output of this interactive code snippet—and run it to check if you were correct!
The challenge in the puzzle is to know that Python comes with implicit Boolean type conversion: every object has an associated Boolean value. Per convention, all objects are True except “empty” or “zero” objects such as [], '', 0, and 0.0. Thus, the result of the function call all([True, True, 0]) is False.
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.
The '_'.join(list) method on the underscore string '_' glues together all strings in the list using the underscore string as a delimiter—and returns a new string. For example, the expression '_'.join(['a', 'b', 'c']) returns the new string 'a_b_c'.
Definition and Usage
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.
The string elements in the list friends are concatenated using the delimiter string '' in the first example and the underscore character '_' in the second example.
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.
Code Puzzle
To practice what you’ve learned so far, feel free to solve the following interactive code puzzle:
Exercise: Guess the output and check if you were right by running the interactive code shell.
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.
Short answer: To flatten your list of list lst, use the nested list comprehension [x for l in lst for x in l] to iterate over all nested lists (for l in lst) and over all their elements (for x in l). Each element x, you just place in the outer list, unchanged.
When browsing StackOverflow, I stumble upon this question from time to time: “How to Join a List of Lists?“. My first thought is that the asking person is referring to the join() function that converts an iterable (such as a list) to a string by concatenating its elements.
But nothing can be further from the truth! The question is usually about “flattening” the list: to transform a nested list of lists such as [[1, 2, 3], [4, 5, 6]] to a flat list [1, 2, 3, 4, 5, 6]. So, the real question is:
How to Flatten a List of Lists in Python?
Problem: Given a list of lists. How to flatten the list of lists by getting rid of the inner lists—and keeping their elements?
Example: You want to transform a given list into a flat list like here:
Solution: Use a nested list comprehension statement [x for l in lst for x in l] to flatten the list.
lst = [[2, 2], [4], [1, 2, 3, 4], [1, 2, 3]] # ... Flatten the list here ...
lst = [x for l in lst for x in l] print(lst)
# [2, 2, 4, 1, 2, 3, 4, 1, 2, 3]
Explanation: In the nested list comprehension statement [x for l in lst for x in l], you first iterate over all lists in the list of lists (for l in lst). Then, you iterate over all elements in the current list (for x in l). This element, you just place in the outer list, unchanged, by using it in the “expression” part of the list comprehension statement [x for l in lst for x in l].
Try It Yourself: You can execute this code snippet yourself in our interactive Python shell. Just click “Run” and test the output of this code.
Exercise: How to flatten a three-dimensional list (= a list of lists of lists)? Try it in the shell!
Video: List Comprehension Python List of Lists
Watch the video to learn three ways how to apply list comprehension to a list of lists:
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.