Jump, shoot, and slash your way through 30XX, the roguelike action platformer you can play with a friend! Explore lush, ever-changing worlds that mix precise platforming with fevered combat. Destroy fearsome Guardians. Master unique Powers. Rediscover the thousand years we've lost.
List comprehension is a concise way to create lists in Python. They offer a shorter syntax to achieve the same result as using a traditional for loop and a conditional statement. List comprehensions make your code more readable and efficient by condensing multiple lines of code into a single line.
The basic syntax for a list comprehension is:
new_list = [expression for element in iterable if condition]
Here, the expression is applied to each element in the iterable (e.g., a list or a range), and the result is appended to the new_list if the optional condition is True. If the condition is not provided, all elements will be included in the new list.
Let’s look at an example. Suppose you want to create a list of squares for all even numbers between 0 and 10. Using a list comprehension, you can write:
squares = [x**2 for x in range(11) if x % 2 == 0]
This single line of code generates the list of squares, [0, 4, 16, 36, 64, 100]. It’s more concise and easier to read compared to using a traditional for loop:
squares = []
for x in range(11): if x % 2 == 0: squares.append(x**2)
You can watch my explainer video on list comprehension here:
For example, you can create a list of all numbers divisible by both 3 and 5 between 1 and 100 with the following code:
divisible = [num for num in range(1, 101) if num % 3 == 0 and num % 5 == 0]
In this case, the resulting list will be [15, 30, 45, 60, 75, 90].
One more advanced feature of Python list comprehensions is the ability to include conditional expressions directly in the expression part, rather than just in the condition.
For example, you can create a list of “even” and “odd” strings based on a range of numbers like this:
even_odd = ["even" if x % 2 == 0 else "odd" for x in range(6)]
This code generates the list ["even", "odd", "even", "odd", "even", "odd"].
If you want to learn to write more concise Python code, check out my book:
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
List comprehensions provide a concise way to make new lists by iterating through an existing list or other iterable object. They are more time and space-efficient than traditional for loops and offer a cleaner syntax.
even_numbers = [x*2 for x in range(5)] # Output: [0, 2, 4, 6, 8]
This creates a new list by multiplying each element within the range(5) function by 2. This compact syntax allows you to define a new list in a single line, making your code cleaner and easier to read.
You can also include a conditional statement within the list comprehension:
even_squares = [x**2 for x in range(10) if x % 2 == 0] # Output: [0, 4, 16, 36, 64]
This example creates a new list of even squares from 0 to 64 by using an if statement to filter out the odd numbers. List comprehensions can also be used to create lists from other iterable objects like strings, tuples, or arrays.
For example, extracting vowels from a string:
text = "List comprehensions in Python"
vowels = [c for c in text if c.lower() in 'aeiou'] # Output: ['i', 'o', 'e', 'e', 'o', 'i', 'o', 'i', 'o']
This will create a list with five None elements. You can then replace them as needed, like placeholder_list[2] = 42, resulting in [None, None, 42, None, None].
Filtering and Transforming Lists
List comprehensions in Python provide a concise way to filter and transform values within an existing list.
Filtering a list involves selecting items that meet a certain condition. You can achieve this using list comprehensions by specifying a condition at the end of the expression.
For example, to create a new list containing only even numbers from an existing list, you would write:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [num for num in numbers if num % 2 == 0]
In this case, the condition is num % 2 == 0. The list comprehension iterates over each item in the numbers list and only includes items where the condition is true.
Aside from filtering, list comprehensions can also transform items in a list. You can achieve this by altering the expression at the beginning of the list comprehension.
For example, to create a list of squares from an existing list, you can use the following code:
squares = [num ** 2 for num in numbers]
Here, the expression num ** 2 transforms each item in the list by squaring it. The squares list will now contain the squared values of the original numbers list.
By combining filtering and transformation, you can achieve even more powerful results in a single, concise statement.
For instance, to create a new list containing the squares of only the even numbers from an existing list, you can write:
even_squares = [num ** 2 for num in numbers if num % 2 == 0]
In this example, we simultaneously filter out odd numbers and square the remaining even numbers.
To further explore list comprehensions, check out these resources on
List comprehensions in Python provide a way to create a new list by filtering and transforming elements of an existing list while significantly enhancing code readability. They enable you to create powerful functionality within a single line of code. Compared to traditional for loops, list comprehensions are more concise and generally preferred in terms of readability.
Here’s an example of using a list comprehension to create a list containing the squares of even numbers in a given range:
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
This single line of code replaces a multiline for loop as shown below:
even_squares = []
for x in range(10): if x % 2 == 0: even_squares.append(x ** 2)
As you can see, the list comprehension is more compact and easier to understand. In addition, it often results in improved performance. List comprehensions are also useful for tasks such as filtering elements, transforming data, and nesting loops.
Here’s another example – creating a matrix transpose using nested list comprehensions:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
This code snippet is equivalent to the nested for loop version:
transpose = []
for i in range(len(matrix[0])): row_list = [] for row in matrix: row_list.append(row[i]) transpose.append(row_list)
While using list comprehensions, be mindful of possible downsides, including loss of readability if the expression becomes too complex. To maintain code clarity, it is crucial to strike the right balance between brevity and simplicity.
List Comprehensions with Different Data Types
List comprehensions work with various data types, such as strings, tuples, dictionaries, and sets.
For example, you can use list comprehensions to perform mathematical operations on list elements. Given a list of integers, you can easily square each element using a single line of code:
num_list = [2, 4, 6]
squared_list = [x**2 for x in num_list]
Handling strings is also possible with list comprehensions. When you want to create a list of the first letters of a list of words, use the following syntax:
words = ["apple", "banana", "cherry"]
first_letters = [word[0] for word in words]
Working with tuples is very similar to lists. You can extract specific elements from a list of tuples, like this:
tuple_list = [(1, 2), (3, 4), (5, 6)]
first_elements = [t[0] for t in tuple_list]
Additionally, you can use list comprehensions with dictionaries. If you have a dictionary and want to create a new one where the keys are the original keys and the values are the squared values from the original dictionary, use the following code:
input_dict = {"a": 1, "b": 2, "c": 3}
squared_dict = {key: value**2 for key, value in input_dict.items()}
Using Functions and Variables in List Comprehensions
List comprehensions in Python are a concise and powerful way to create new lists by iterating over existing ones. They provide a more readable alternative to using for loops and can easily add multiple values to specific keys in a dictionary.
When it comes to using functions and variables in list comprehensions, it’s important to keep the code clear and efficient. Let’s see how to incorporate functions, variables, and other elements mentioned earlier:
Using Functions in List Comprehensions You can apply a function to each item in the list using a comprehension. Here’s an example with the upper() method:
letters = ['a', 'b', 'c', 'd']
upper_letters = [x.upper() for x in letters]
This comprehension will return a new list containing the uppercase versions of each letter. Any valid function can replace x.upper() to apply different effects on the input list.
Utilizing Variables in List Comprehensions With variables, you can use them as a counter or a condition. For example, a list comprehension with a counter:
squares = [i**2 for i in range(1, 6)]
This comprehension creates a list of squared numbers from 1 to 5. The variable i is a counter that iterates through the range() function.
For a more complex example, let’s say we want to filter out odd numbers from a list using the modulo % operator:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [x for x in numbers if x % 2 == 0]
In this case, the variable x represents the current element being manipulated during the iteration, and it is used in the condition x % 2 == 0 to ensure we only keep even numbers.
Working with Nested List Comprehensions
Nested list comprehensions in Python are a versatile and powerful feature that allows you to create new lists by applying an expression to an existing list of lists. This is particularly useful for updating or traversing nested sequences in a concise and readable manner.
I created a video on nested list comprehensions here:
A nested list comprehension consists of a list comprehension inside another list comprehension, much like how nested loops work. It enables you to iterate over nested sequences and apply operations to each element.
For example, consider a matrix represented as a list of lists:
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]
]
To calculate the square of each element in the matrix using nested list comprehensions, you can write:
squared_matrix = [[x**2 for x in row] for row in matrix]
This code is equivalent to the following nested for loop:
squared_matrix = []
for row in matrix: squared_row = [] for x in row: squared_row.append(x**2) squared_matrix.append(squared_row)
As you can see, the nested list comprehension version is much more concise and easier to read.
Python supports various sequences like lists, tuples, and dictionaries. You can use nested list comprehensions to create different data structures by combining them. For instance, you can convert the matrix above into a dictionary where keys are the original numbers and values are their squares:
matrix_dict = {x: x**2 for row in matrix for x in row}
List comprehension is a powerful feature in Python that allows you to quickly create new lists based on existing iterables. They provide a concise and efficient way of creating new lists with a few lines of code.
The first advanced technique to consider is using range() with index. By utilizing the range(len(...)) function, you can iterate over all the items in a given iterable.
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
In addition to creating new lists, you can also use conditional statements in list comprehensions for more control over the output.
For example, if you want to create a new list with only the even numbers from an existing list, you can use a condition like this:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
Another useful feature is the access of elements in an iterable using their index. This method enables you to modify the output based on the position of the elements:
words = ["apple", "banana", "cherry", "date"]
capitals = [word.capitalize() if i % 2 == 0 else word for i, word in enumerate(words)]
In this example, the enumerate() function is used to get both the index (i) and the element (word). The even-indexed words are capitalized, and the others remain unchanged.
Moreover, you can combine multiple iterables using the zip() function. This technique allows you to access elements from different lists simultaneously, creating new lists based on matched pairs.
x = [1, 2, 3]
y = [4, 5, 6]
combined = [a + b for a, b in zip(x, y)]
Frequently Asked Questions
What is the syntax for list comprehensions with if-else statements?
List comprehensions allow you to build lists in a concise way. To include an if-else statement while constructing a list, use the following syntax:
new_list = [expression_if_true if condition else expression_if_false for item in iterable]
For example, if you want to create a list of numbers, where even numbers are squared and odd numbers remain unchanged:
numbers = [1, 2, 3, 4, 5]
new_list = [number ** 2 if number % 2 == 0 else number for number in numbers]
How do you create a dictionary using list comprehension?
You can create a dictionary using a dict comprehension, which is similar to a list comprehension. The syntax is:
new_dict = {key_expression: value_expression for item in iterable}
For example, creating a dictionary with square values as keys and their roots as values:
squares = {num ** 2: num for num in range(1, 6)}
How can you filter a list using list comprehensions?
Filtering a list using list comprehensions involves combining the basic syntax with a condition. The syntax is:
filtered_list = [expression for item in iterable if condition]
For example, filtering out even numbers from a given list:
numbers = [1, 2, 3, 4, 5]
even_numbers = [number for number in numbers if number % 2 == 0]
What is the method to use list comprehension with strings?
List comprehensions can be used with any iterable, including strings. To create a list of characters from a string using list comprehension:
text = "Hello, World!"
char_list = [char for char in text]
How do you combine two lists using list comprehensions?
To combine two lists using list comprehensions, use a nested loop. Here’s the syntax:
combined_list = [expression for item1 in list1 for item2 in list2]
For example, combining two lists containing names and ages:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = [f"{name} is {age} years old" for name in names for age in ages]
What are the multiple conditions in a list comprehension?
When using multiple conditions in a list comprehension, you can have multiple if statements after the expression. The syntax is:
new_list = [expression for item in iterable if condition1 if condition2]
For example, creating a list of even numbers greater than 10:
numbers = list(range(1, 20))
result = [number for number in numbers if number % 2 == 0 if number > 10]
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Do you want to upload an image to the database? Most application services move the uploaded files to a directory and save their path to the database.
Earlier, we saw code for storing uploaded images to the database using MySQL BLOB fields. BLOB(Binary Large Data Object) is one of the MySql data types. It can have the file binary data. MySQL supports four types of BLOB datatype as follows. View demo
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
For this example, we created one of the above BLOB fields in a MySQL database to see how to upload an image. Added to that, this code will fetch and BLOB data from the database and display the image to the browser.
Database script
Before running this example, create the required database structure on your server.
CREATE TABLE images ( id INT(11) AUTO_INCREMENT PRIMARY KEY, image LONGBLOB NOT NULL );
HTML form with an image upload option
This is a usual file upload form with a file input. This field restricts the file type to choose only the images using the accept attribute.
On submitting this form, the upload.php receives the posted file binary data on the server side.
Insert an image into the database using PHP and MySql
This PHP script gets the chosen file data with the $_FILES array. This array contains the base name, temporary source path, type, and more details.
With these details, it performs the file upload to the database. The steps are as follows,
Validate file array is not empty.
Retrieve the image file content using file_get_contents($_FILES[“image”][“tmp_name”]).
Prepare the insert and bind the image binary data to the query parameters.
Execute insert and get the database record id.
<?php
// MySQL database connection settings
$servername = "localhost";
$username = "root";
$password = "admin123";
$dbname = "phppot_image_upload"; // Make connection
$conn = new mysqli($servername, $username, $password, $dbname); // Check connection and throw error if not available
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
} // Check if an image file was uploaded
if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) { $image = $_FILES['image']['tmp_name']; $imgContent = file_get_contents($image); // Insert image data into database as BLOB $sql = "INSERT INTO images(image) VALUES(?)"; $statement = $conn->prepare($sql); $statement->bind_param('s', $imgContent); $current_id = $statement->execute() or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_connect_error()); if ($current_id) { echo "Image uploaded successfully."; } else { echo "Image upload failed, please try again."; }
} else { echo "Please select an image file to upload.";
} // Close the database connection
$conn->close();
Fetch image BLOB from the database and display to UI
This PHP code prepares a SELECT query to fetch the image BLOB. Using the image binary from the BLOB, it creates the data URL. It applies PHP base64 encoding on the image binary content.
This data URL is set as a source of an HTML image element below. This script shows the recently inserted image on the screen. We can also show an image gallery of all the BLOB images from the database.
<?php // Retrieve the uploaded image from the database $servername = "localhost"; $username = "root"; $password = ""; $dbname = "phppot_image_upload"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $result = $conn->query("SELECT image FROM images ORDER BY id DESC LIMIT 1"); if ($result && $result->num_rows > 0) { $row = $result->fetch_assoc(); $imageData = $row['image']; echo '<img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" alt="Uploaded Image" style="max-width: 500px;">'; } else { echo 'No image uploaded yet.'; } $conn->close(); ?>
VORAX is an Open World Survival Horror game set on a Mediterranean island where a mysterious pathogen has infected the local population. https://youtu.be/eicLq7pU4g0
Posted by: xSicKxBot - 08-23-2023, 03:13 AM - Forum: Python
- No Replies
[Tut] 8 Millionaire Tips to Reach Financial Freedom as a Coder
5/5 – (1 vote)
If you’re like me, you don’t want to hear tips from people who haven’t been there and done that, so let’s start with a few words on my financial situation:
About Me: My investments and business portfolio is worth north of one million USD at the time of writing. While I’m technically financially free in that I don’t have to work anymore to maintain my lifestyle, I love business and finances, so I keep writing blogs for Finxter.
For some readers, my financial situation may be uninterestingly low. Others may find it significant. Only you can judge if I’m the right person for you to take seriously. Finally, this is not investment advice but educational entertainment.
With this out of the way, let’s get started with the slow lane to becoming a millionaire:
Five Millionaire Tips From the Slow Lane
The National Study of Millionaires by Ramsey Solutions provides valuable insights into the financial habits and behaviors of millionaires in the United States.
Contrary to popular belief, the majority of millionaires did not inherit their wealth, nor did they earn it through high salaries or risky investments.
Instead, they achieved their financial success through consistent investing, avoiding debt, and smart spending. Let’s recap these points as they are important:
Consistent Investing
Avoiding Debt
Smart Spending
Here are some key takeaways from the study, particularly relevant for techies and coders:
Millionaire Tip #1 – Invest Consistently
Three out of four millionaires (75%) attributed their success to regular, consistent investing over a long period of time. This is a crucial lesson for tech professionals, who often have access to employer-sponsored retirement plans like 401(k)s. By consistently contributing to these plans and taking advantage of employer matching, techies can build substantial wealth over time.
I have written a blog post about the math of consistent investments as a coder for various specific situations:
Nearly three-quarters of the millionaires surveyed have never carried a credit card balance. For tech professionals, who may face student loan debt or the temptation to overspend on gadgets and tech gear, it’s essential to prioritize paying off debt and avoiding new debt. This will free up more money for investing and reduce the financial stress that comes with carrying debt.
The only debt acceptable is debt to build financial assets such as a business or investments (e.g., real estate) because it can help you inject leverage and financial horsepower into your life.
However, the risk is significant, and even if financial leverage can accelerate your wealth-building journey, it can cost you dearly: every number, no matter how large, multiplied by zero is zero.
Millionaire Tip #3 – Spend Smartly
The study found that 94% of millionaires live on less than they make, and 93% use coupons when shopping. Tech professionals can adopt similar frugal habits by budgeting, tracking expenses, and looking for ways to save money on everyday purchases. This will allow them to invest more and reach their financial goals faster.
Millionaire Tip #4 – Educate Yourself
The majority of millionaires in the study graduated from college, with over half (52%) earning a master’s or doctoral degree. For tech professionals, continuing education and skill development can lead to higher earning potential and career advancement. Whether it’s pursuing advanced degrees, certifications, or online courses, investing in education can pay off in the long run.
The Finxter Academy, for example, provides relevant tech courses with certifications you can use to showcase your skills to potential employers such as Google, Facebook, Amazon, OpenAI, or Tesla.
Millionaire Tip #5 – Focus on the Right Career
The top five careers for millionaires in the study include engineer, accountant, teacher, management, and attorney. For techies, pursuing a career in engineering or management can be a path to financial success. However, it’s essential to remember that hard work and dedication are more critical factors than job title or salary. In fact, 93% of millionaires said they got their wealth because they worked hard, not because they had big salaries.
As my blog post “Millionaire Math” outlines, there are many paths to financial freedom, but all of them require a savings rate of 10% or (much) higher.
In conclusion, becoming a millionaire in the US is achievable for tech professionals who are willing to invest consistently, avoid debt, spend wisely, and work hard. By adopting the financial habits and behaviors of millionaires, techies can build substantial wealth and achieve their financial goals.
Three Millionaire Tips From The Fast Lane
The slow lane is good enough to becoming a millionaire coder. Many have done it. You can do it too. But becoming rich young may be even more attractive for you.
In that case, you have other options you can employ in addition to (not necessarily instead of) the slow lane:
Millionaire Tip #6 – Leverage Scalable Business Models
A coder creates a software application that solves a specific problem for a niche market. Over time, the app gains traction and attracts a large user base. The coder monetizes the app through a subscription model, generating $500,000 in annual revenue. After a few years of consistent growth, a larger software company takes notice and offers to acquire the app for $2.5 million at a 5x revenue multiple. The coder accepts the offer and experiences an explosive wealth event by selling the app.
Stories like these happen every day. The odds are much higher than playing the lottery — in fact, many savvy entrepreneurs have proven that this strategy is replicable. I have built roughly three-quarters of my wealth by leveraging scalable business models and asset value through the profit multiple.
Below is an expanded table of profit multiples and example business valuations for one-person coding startups, along with example businesses that a one-person coder could realistically build.
Profit Multiple
Annual Net Profit
Business Valuation
Example Business
2x
$50,000
$100,000
A mobile app for time management
3x
$100,000
$300,000
A SaaS platform for small business accounting
4x
$150,000
$600,000
A web application for project management
5x
$200,000
$1,000,000
A cryptocurrency trading bot
6x
$300,000
$1,800,000
A machine learning tool for data analysis
7x
$500,000
$3,500,000
A blockchain platform for supply chain tracking
8x
$1,000,000
$8,000,000
A cybersecurity software for enterprise protection
9x
$2,000,000
$18,000,000
A cloud-based platform for IoT device management
10x
$5,000,000
$50,000,000
A virtual reality platform for education
11x
$9,090,909
$100,000,000
An AI-powered platform for personalized marketing
It’s important to note that achieving a business valuation of $100 million as a one-person coder is a significant accomplishment and would likely require a highly innovative and scalable technology, a large addressable market, and strong competitive advantages. Additionally, as the business grows, it may be necessary to hire additional team members, seek external funding, and expand the business’s operations.
It’s also worth noting that the profit multiples used in the table are for illustrative purposes and may vary based on the specific circumstances of the business. Factors such as growth potential, competitive landscape, and risk profile can all influence the profit multiple and business valuation.
One-person coders have the potential to build valuable businesses by leveraging their technical skills and entrepreneurial mindset. By creating innovative and scalable technology solutions, coders can address market needs, generate revenue, and achieve significant business valuations.
Millionaire Tip #7 – Monetize Open-Source Contributions
A coder contributes to an open-source project that becomes widely used in the tech industry. The coder decides to offer premium features and support services for a fee. The coder’s contributions and premium offerings become so popular that they generate $200,000 in annual revenue. A venture capital firm recognizes the potential of the project and offers to invest $1 million in exchange for a minority stake in the coder’s business. The coder agrees to the investment, which provides an immediate influx of capital and an explosive wealth event.
Here are five real examples of open-source developers who have created significant wealth as a result of their open-source work:
Linus Torvalds: Linus Torvalds is the creator of the Linux kernel, which is the foundation of the Linux operating system. Linux is one of the most successful open-source projects in history and is used by millions of servers, desktops, and embedded systems worldwide. Torvalds has earned significant wealth through his work on Linux, including awards, speaking engagements, and his role as a Fellow at the Linux Foundation.
Guido van Rossum: Guido van Rossum is the creator of the Python programming language, which is one of the most popular programming languages in the world. Python is used for web development, data analysis, machine learning, and more. Van Rossum has earned significant wealth through his work on Python, including his role as a software engineer at Google and later as a Distinguished Engineer at Microsoft.
Matt Mullenweg: Matt Mullenweg is the co-founder of WordPress, the most popular content management system (CMS) in the world. WordPress is an open-source project that powers over 40% of all websites on the internet. Mullenweg has earned significant wealth through his work on WordPress, including his role as the CEO of Automattic, the company behind WordPress.com, WooCommerce, and other products.
Dries Buytaert: Dries Buytaert is the creator of Drupal, an open-source CMS that is used by many large organizations, including NASA, the White House, and the BBC. Buytaert has earned significant wealth through his work on Drupal, including his role as the co-founder and CTO of Acquia, a company that provides cloud hosting and support for Drupal sites.
John Resig: John Resig is the creator of jQuery, a popular JavaScript library that simplifies web development. jQuery is used by millions of websites and has become a standard tool for web developers. Resig has earned significant wealth through his work on jQuery, including his role as a software engineer at Khan Academy and his work as an author and speaker.
Millionaire Tip #8 – Build Multiple Income Streams
A coder starts a side hustle offering tech consulting services to small businesses. Over time, the coder’s reputation grows, and the consulting business generates $250,000 in annual revenue. The coder decides to scale the business by hiring additional consultants and expanding the service offerings. After a few years of growth, a larger consulting firm approaches the coder with an offer to acquire the business for $1 million at a 4x revenue multiple. The coder accepts the offer and experiences an explosive wealth event by selling the consulting business.
During all this time building the successful venture on the side, the coder also had a full-time income from their job and investment portfolio — multiple income streams!
In each of these scenarios, you leverage your technical skills and entrepreneurial mindset to create value and generate revenue. By seizing opportunities and making strategic decisions, you can experience explosive wealth events that significantly increase your net worth.
Feel free to read our advanced article on the math of becoming a millionaire:
Rise from the dust and liberate mankind from the oppression of corrupted gods. Glide the sands of a timeless land, filled with ancient dangers, mysteries and fragments of the past. Hunt legendary monsters, using powerful, shape-shifting weapons and devastating sand-powered abilities in spectacular, super-powered combat.
Target and gather the essence of your enemies to shape your own custom playstyle, forging a new era for humanity in a fully cooperative or solo story campaign.
Posted by: xSicKxBot - 08-22-2023, 09:07 AM - Forum: Python
- No Replies
[Tut] Python IndexError: Tuple Index Out of Range [Easy Fix]
5/5 – (1 vote)
Key Points:
To solve the “IndexError: tuple index out of range”, avoid do not access a non-existing tuple index. For example, my_tuple[5] causes an error for a tuple with three elements.
If you access tuple elements in a loop, keep in mind that Python uses zero-based indexing: For a tuple with n elements, the first element has index 0 and the last index n-1.
A common cause of the error is trying to access indices 1, 2, ..., n instead of using the correct indices 0,1, ..., (n-1).
The following video shows how I fixed a similar error on a list instead of a tuple:
If you’re like me, you try things first in your code and fix the bugs as they come.
One frequent bug in Python is the IndexError: tuple index out of range. So, what does this error message mean?
The error “tuple index out of range” arises if you access invalid indices in your Python tuple. For example, if you try to access the tuple element with index 100 but your tuple consist only of three elements, Python will throw an IndexError telling you that the tuple index is out of range.
Minimal Example
Here’s a screenshot of this happening on my Windows machine:
Let’s have a look at an example where this error arises:
The element with index 3 doesn’t exist in the tuple with three elements. Why is that?
The following graphic shows that the maximal index in your tuple is 2. The call my_tuple[2] would retrieve the third tuple element 'Carl'.
my_tuple[0] --> Alice
my_tuple[1] --> Bob
my_tuple[2] --> Carl
my_tuple[3] --> ??? Error ???
Did you try to access the third element with index 3?
It’s a common mistake: The index of the third element is 2 because the index of the first tuple element is 0.
How to Fix the IndexError in a For Loop? [General Strategy]
So, how can you fix the code? Python tells you in which line and on which tuple the error occurs.
To pin down the exact problem, check the value of the index just before the error occurs.
To achieve this, you can print the index that causes the error before you use it on the tuple. This way, you’ll have your wrong index in the shell right before the error message.
Here’s an example of wrong code that will cause the error to appear:
# WRONG CODE
my_tuple = ('Alice', 'Bob', 'Ann', 'Carl') for i in range(len(my_tuple)+1): my_tuple[i] ''' OUTPUT
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 5, in <module> my_tuple[i]
IndexError: tuple index out of range '''
The error message tells you that the error appears in line 5.
So, let’s insert a print statement before that line:
my_tuple = ('Alice', 'Bob', 'Ann', 'Carl') for i in range(len(my_tuple)+1): print(i) my_tuple[i]
The result of this code snippet is still an error.
But there’s more:
0
1
2
3
4
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 6, in <module> my_tuple[i]
IndexError: tuple index out of range
You can now see all indices used to retrieve an element.
The final one is the index i=4 which points to the fifth element in the tuple (remember zero-based indexing: Python starts indexing at index 0!).
But the tuple has only four elements, so you need to reduce the number of indices you’re iterating over.
The correct code is, therefore:
# CORRECT CODE
my_tuple = ('Alice', 'Bob', 'Ann', 'Carl') for i in range(len(my_tuple)): my_tuple[i]
Note that this is a minimal example and it doesn’t make a lot of sense. But the general debugging strategy remains even for advanced code projects:
Figure out the faulty index just before the error is thrown.
Eliminate the source of the faulty index.
Programmer Humor
“Real programmers set the universal constants at the start such that the universe evolves to contain the disk with the data they want.” — xkcd
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
A gauge chart is a scale to measure performance amid the target. Yeah! My attempt at defining ‘Gauge.’ This article uses the ChartJS JavaScript library to create a gauge chat.
The below example creates a speedometer in the form of a gauge change. It achieves this with type=doughnut. The other options, cutout, rotation, and circumference, make the expected gauge chart view. View Demo
<!DOCTYPE html>
<html> <head> <title>Gauge Chart Example using Chart.js</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head> <body> <canvas id="gaugeChart"></canvas> <script> // data for the gauge chart // you can supply your own values here // max is the Gauge's maximum value var data = { value: 200, max: 300, label: "Progress" }; // Chart.js chart's configuration // We are using a Doughnut type chart to // get a Gauge format chart // This is approach is fine and actually flexible // to get beautiful Gauge charts out of it var config = { type: 'doughnut', data: { labels: [data.label], datasets: [{ data: [data.value, data.max - data.value], backgroundColor: ['rgba(54, 162, 235, 0.8)', 'rgba(0, 0, 0, 0.1)'], borderWidth: 0 }] }, options: { responsive: true, maintainAspectRatio: false, cutoutPercentage: 85, rotation: -90, circumference: 180, tooltips: { enabled: false }, legend: { display: false }, animation: { animateRotate: true, animateScale: false }, title: { display: true, text: data.label, fontSize: 16 } } }; // Create the chart var chartCtx = document.getElementById('gaugeChart').getContext('2d'); var gaugeChart = new Chart(chartCtx, config); </script>
</body> </html>
The above quick example script follows the below steps to render a gauge chart with the data and the options.
Many of the steps are similar to that of creating any other chart using this library. We have seen many examples in the ChartJS library. You can start with the ChartJS bar chart example if you are new to this JavaScript library.
The data and options are the main factors that change the chart view. This section has short notes for more information about the data and the options array created in JavaScript.
This JavaScript example uses an array of static data to form a gauge chart. You can supply dynamic data from the database or any external source instead.
The data array has the chart label, target, and current value. The target value is the maximum limit of the gauge chart scale. The current value is an achieved point to be marked.
Using these values, this script prepares the gauge chart dataset.
The options array is a configuration that affects the chart’s appearance.
The ChartJS allows featured configurations to experience the best chart views. Some of those options exclusive to the gauge chart are listed below.