This is a tutorial video from my new book “Python One-Liners” with NoStarch press (San Francisco 2020).
Grab your Python One-Liner Superpower now! (Amazon Link)
Here’s the code that shows you how to sample a two-dimensional Python list—including only every other list element in the resulting two-dimensional Python list. All of this happens in a single line of code:
## Data (daily stock prices ($)) price = [[9.9, 9.8, 9.8, 9.4, 9.5, 9.7], [9.5, 9.4, 9.4, 9.3, 9.2, 9.1], [8.4, 7.9, 7.9, 8.1, 8.0, 8.0], [7.1, 5.9, 4.8, 4.8, 4.7, 3.9]] sample = [line[::2] for line in price] print(sample) # [[9.9, 9.8, 9.5], [9.5, 9.4, 9.2], [8.4, 7.9, 8.0], [7.1, 4.8, 4.7]]
Try it yourself:
The code simply removes every other element from each row in the 2D matrix.
Check out the following Finxter tutorials to learn about the necessary background:
Related articles:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.