Posted on Leave a comment

Python Join List of DataFrames

To join a list of DataFrames, say dfs, use the pandas.concat(dfs) function that merges an arbitrary number of DataFrames to a single one.

When browsing StackOverflow, I recently stumbled upon the following interesting problem. By thinking about solutions to those small data science problems, you can improve your data science skills, so let’s dive into the problem description.

Problem: Given a list of Pandas DataFrames. How to merge them into a single DataFrame?

Example: You have the list of Pandas DataFrames:

df1 = pd.DataFrame({'Alice' : [18, 'scientist', 24000], 'Bob' : [24, 'student', 12000]})
df2 = pd.DataFrame({'Alice' : [19, 'scientist', 25000], 'Bob' : [25, 'student', 11000]})
df3 = pd.DataFrame({'Alice' : [20, 'scientist', 26000], 'Bob' : [26, 'student', 10000]}) # List of DataFrames
dfs = [df1, df2, df3]

Say, you want to get the following DataFrame:

 Alice Bob
0 18 24
1 scientist student
2 24000 12000
0 19 25
1 scientist student
2 25000 11000
0 20 26
1 scientist student
2 26000 10000

You can try the solution quickly in our interactive Python shell:

Exercise: Print the resulting DataFrame. Run the code. Which merging strategy is used?

Method 1: Pandas Concat

This is the easiest and most straightforward way to concatenate multiple DataFrames.

import pandas as pd df1 = pd.DataFrame({'Alice' : [18, 'scientist', 24000], 'Bob' : [24, 'student', 12000]})
df2 = pd.DataFrame({'Alice' : [19, 'scientist', 25000], 'Bob' : [25, 'student', 11000]})
df3 = pd.DataFrame({'Alice' : [20, 'scientist', 26000], 'Bob' : [26, 'student', 10000]}) # list of dataframes
dfs = [df1, df2, df3] df = pd.concat(dfs)

This generates the following output:

print(df) ''' Alice Bob
0 18 24
1 scientist student
2 24000 12000
0 19 25
1 scientist student
2 25000 11000
0 20 26
1 scientist student
2 26000 10000 '''

The resulting DataFrames contains all original data from all three DataFrames.

Method 2: Reduce + DataFrame Merge

The following method uses the reduce function to repeatedly merge together all dictionaries in the list (no matter its size). To merge two dictionaries, the df.merge() method is used. You can use several merging strategies—in the example, you use "outer":

import pandas as pd df1 = pd.DataFrame({'Alice' : [18, 'scientist', 24000], 'Bob' : [24, 'student', 12000]})
df2 = pd.DataFrame({'Alice' : [19, 'scientist', 25000], 'Bob' : [25, 'student', 11000]})
df3 = pd.DataFrame({'Alice' : [20, 'scientist', 26000], 'Bob' : [26, 'student', 10000]}) # list of dataframes
dfs = [df1, df2, df3] # Method 2
from functools import reduce
df = reduce(lambda df1, df2: df1.merge(df2, "outer"), dfs)

This generates the following output:

print(df) ''' Alice Bob
0 18 24
1 scientist student
2 24000 12000
3 19 25
4 25000 11000
5 20 26
6 26000 10000 '''

You can find a discussion of the different merge strategies here. If you’d use the parameter "inner", you’d obtain the following result:

 Alice Bob
0 scientist student

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

wren Programming Language

Very similar in scope and purpose to the recently covered Gravity language, today we are looking at wren.  wren is a class based programming language that aims to bring Smalltalk like programming to a Lua sized footprint, with the intention of being embedded in application code.  Highlights of wren include:

  • Wren is small. The VM implementation is under 4,000 semicolons. You can skim the whole thing in an afternoon. It’s small, but not dense. It is readable and lovingly-commented.

  • Wren is fast. A fast single-pass compiler to tight bytecode, and a compact object representation help Wren compete with other dynamic languages.

  • Wren is class-based. There are lots of scripting languages out there, but many have unusual or non-existent object models. Wren places classes front and center.

  • Wren is concurrent. Lightweight fibers are core to the execution model and let you organize your program into an army of communicating coroutines.

  • Wren is a scripting language. Wren is intended for embedding in applications. It has no dependencies, a small standard library, and an easy-to-use C API. It compiles cleanly as C99, C++98 or anything later.

Wren is open source under the MIT license with the source available on GitHub.  You can also try out the wren language in your browser using this handy site.  You can learn more about wren in the video below.

GameDev News Programming


Posted on Leave a comment

How to Get a List Slice with Arbitrary Indices in Python?

To extract elements with specific indices from a Python list, use slicing list[start:stop:step]. If you cannot use slicing because there’s no pattern in the indices you want to access, use the list comprehension statement [lst[i] for i in indices], assuming your indices are stored in the variable indices.

People always want to know the most Pythonic solution to a given problem. This tutorial shows you the most Pythonic solution(s) to the following problem:

Problem: How to extract elements with specific indices from a Python list?

Example: You’ve got the following elements.

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

You want to create a new list of elements with indices = [0, 2, 6] in the original list:

['a', 'c', 'g']
How to get elements with specific indices from a Python list?

You can get a quick overview of the most Pythonic methods in our interactive Python shell:

Exercise: Run the code shell. Now, try to access the element with index 7 as well in each of the given methods!

Method 1: List Comprehension

A simple, readable, and efficient way is to use list comprehension that’s 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.

Here’s the code that creates a new list that contains the elements at specific indices (e.g., 0, 2, and 6) in the original list:

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = [lst[i] for i in indices]
print(out)
# ['a', 'c', 'g']

In most cases, this will be the best solution because you don’t need any library and it’s still short and readable. However, if you need to do this multiple times, it may be better to import the NumPy library:

Method 2: NumPy Array Indexing

Python’s library for numerical computations, NumPy, is one of the most powerful tools in your toolbelt—especially if you work as a data scientist. Here’s how you can use NumPy to access arbitrary indices, given a sequence of specific indices:

import numpy as np
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a = np.array(lst)
indices = [0, 2, 6] out = a[indices]

The output is:

print(out)
# ['a' 'c' 'g']

You see that NumPy indexing is far more powerful than Python indexing—it allows you to use arbitrary sequences as indices. Especially, if you need to do multiple of those numerical operations, you may want to import the NumPy library once and gain much in readability and conciseness.

Related resources:

Method 3: Itemgetter

The following method can be seen sometimes—using the itemgetter function from the operator module:

from operator import itemgetter
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = list(itemgetter(*indices)(lst))
print(out)
# ['a', 'c', 'g']

The code performs the following steps:

  • Call the itemgetter() function and pass the arguments 0, 2, and 6. We use the asterisk operator * to unpack the values from the indices variable into the itemgetter() function. Learn more about the asterisk operator in our detailed blog article.
  • This returns a new itemgetter function object.
  • Call the new itemgetter function object by passing the original list lst.
  • The new itemgetter function will now get a tuple of the items at positions 0, 2, and 6 in the original list lst.
  • Convert the tuple to a list using the list(...) built-in Python function.

Method 4: Manual Indices

Just for comprehensibility, I also want to point out the “naive” way of accessing a few elements in the original list and put them into a new list:

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
out = [lst[0], lst[2], lst[6]]
print(out)
# ['a', 'c', 'g']

This is a perfectly valid and efficient approach if you have only a few elements to access. For more than, say, five indices, it quickly becomes unhandy though.

Method 5: Simple Loop

Here’s another approach that’s often used by coders who come from other programming languages such as Java or C++: using simple loops.

lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
indices = [0, 2, 6]
out = []
for i in indices: out.append(lst[i])
print(out)
# ['a', 'c', 'g']

While there’s nothing wrong with this, it looks somehow “brutal” to an advanced coder. If you’d use this method, it would be like shouting into the world that you’re not a very sophisticated Python coder. 😉

Nothing wrong with that—don’t get me wrong! But if you want to increase your level of sophistication in Python, join my free email academy with many Python email courses that will sharpen your skills! Have I already said that it’s free?

Join Python Email Academy!

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 Convert a List to a NumPy Array?

To convert a Python list to a NumPy array, use either of the following two methods:

  1. The np.array() function that takes an iterable and returns a NumPy array creating a new data structure in memory.
  2. The np.asarray() function that takes an iterable as argument and converts it to the array. The difference to np.array() is that np.asarray() doesn’t create a new copy in memory if you pass a NumPy array. All changes made on the original array are reflected on the NumPy array.

Exercise: Create array b from array a using both methods. Then change a value in array a. What happens at array b?

NumPy vs Python Lists

The Python built-in list data type is powerful. However, the NumPy array has many advantages over Python lists. What are they?

Advantages NumPy Advantages Python Lists
Multi-dimensional Slicing Library-Independent
Broadcasting Functionality Intuitive
Processing Speed Less Complicated
Memory Footprint Heterogeneous List Data Allowed
Many Convenience Methods Arbitrary Data Shape (Non-Square Matrix)

To read more about the advantages of a NumPy array over a Python list, read my detailed blog tutorial.

How to Convert a 1D Python List to a NumPy Array?

Problem: Given a one-dimensional Python list. How to convert it to a NumPy array?

Example: You have the following 1D Python list of integers.

lst = [0, 1, 100, 42, 13, 7]

You want to convert it into a NumPy array.

array([ 0, 1, 100, 42, 13, 7])

Method 1: np.array(…)

The simplest way to convert a Python list to a NumPy array is to use the np.array() function that takes an iterable and returns a NumPy array.

import numpy as np
lst = [0, 1, 100, 42, 13, 7]
print(np.array(lst))

The output is:

# [ 0 1 100 42 13 7]

This creates a new data structure in memory. Changes on the original list are not visible to the variable that holds the NumPy array:

lst = [0, 1, 100, 42, 13, 7]
a = np.array(lst)
lst.append(999)
print(a)
# [ 0 1 100 42 13 7]

The element 999 which is now part of list lst is not part of array a.

Method 2: np.asarray(…)

An alternative is to use the np.asarray() function that takes one argument—the iterable—and converts it to the NumPy array. The difference to np.array() is that it doesn’t create a new copy in memory IF you pass a NumPy array. All changes made on the original array are reflected on the NumPy array! So be careful.

lst = [0, 1, 100, 42, 13, 7]
a = np.array(lst)
b = np.asarray(a)
a[0] = 99
print(b)
# [ 99 1 100 42 13 7]

The array b is created using the np.asarray() function, so if you change a value of array a, the change will be reflected on the variable b (because they point to the same object in memory).

[Video] How to Convert a List of Lists to a NumPy Array?

Convert List of Lists to 2D Array

Problem: Given a list of lists in Python. How to convert it to a 2D NumPy array?

Example: Convert the following list of lists

[[1, 2, 3], [4, 5, 6]]

into a NumPy array

[[1 2 3] [4 5 6]]

Solution: Use the np.array(list) function to convert a list of lists into a two-dimensional NumPy array. Here’s the code:

# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5, 6]] # Convert it to a NumPy array
a = np.array(lst) # Print the resulting array
print(a) '''
[[1 2 3] [4 5 6]] '''

Try It Yourself: Here’s the same code in our interactive code interpreter:

<iframe height="700px" width="100%" src="https://repl.it/@finxter/numpylistoflists?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>

Hint: The NumPy method np.array() takes an iterable as input and converts it into a NumPy array.

Convert a List of Lists With Different Number of Elements

Problem: Given a list of lists. The inner lists have a varying number of elements. How to convert them to a NumPy array?

Example: Say, you’ve got the following list of lists:

[[1, 2, 3], [4, 5], [6, 7, 8]]

What are the different approaches to convert this list of lists into a NumPy array?

Solution: There are three different strategies you can use. (source)

(1) Use the standard np.array() function.

# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array
a = np.array(lst) # Print the resulting array
print(a) '''
[list([1, 2, 3]) list([4, 5]) list([6, 7, 8])] '''

This creates a NumPy array with three elements—each element is a list type. You can check the type of the output by using the built-in type() function:

>>> type(a)
<class 'numpy.ndarray'>

(2) Make an array of arrays.

# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array
a = np.array([np.array(x) for x in lst]) # Print the resulting array
print(a) '''
[array([1, 2, 3]) array([4, 5]) array([6, 7, 8])] '''

This is more logical than the previous version because it creates a NumPy array of 1D NumPy arrays (rather than 1D Python lists).

(3) Make the lists equal in length.

# Import the NumPy library
import numpy as np # Create the list of lists
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Calculate length of maximal list
n = len(max(lst, key=len)) # Make the lists equal in length
lst_2 = [x + [None]*(n-len(x)) for x in lst]
print(lst_2)
# [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]] # Convert it to a NumPy array
a = np.array(lst_2) # Print the resulting array
print(a) '''
[[1 2 3 None] [4 5 None None] [6 7 8 9]] '''

You use list comprehension to “pad” None values to each inner list with smaller than maximal length.

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

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!