Building a list is a very specific building block in learning code, being a data analyst, or whatever data driven role you find yourself sitting in.
Python List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. (from python)
What is list comprehensions? i for i
List comprehensions is the name of a way to create lists. A more technical rationale would be that list comprehensions provide a more concise way to create lists.
Before we begin, let’s discuss two simple methods to printing our list comprehensions.
print [i for i in range(3)]
Or we can use a letter, word, or letters+words. We will only use this method below.
x = [i for i in range(3)]
Below, I will explain how to use list comprehensions, what list comprehensions is all about, and various ways to use list comprehensions when utilizing Python! Woohoo, getting excited, I can tell. (I can’t, I’m weird)
What is the goal with list comprehensions?
It is proposed to allow conditional construction of list literals using for and if clauses. It’s like you haven’t heard of either of these today, if so, go check out python’s website on list comprehensions. If this does make sense, you may also be interested to know the proposed solution not only lets you generate conditional lists with for and if, they would nest the same way for loops and if statements nest now.
About the tutorials below.
If you’re not entirely sure what any of the above text means, woohoo. You’re on the right track, you’re on the right blog, and if you do know the techie words above, but not entirely sure what it means in code, or in python… Check it out…
Tutorial 1, making a simple list of data in python using List Comprehensions
There are two different ways to make a list of numbers in python.
Take a look at List Comprehension and another more complicated method.
Assuming you have a basic python install and you’re able to do the 2+2 to get 4 in python.
Easy method to make a simple list in python.
x = [i for i in range(10)]
## >>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Complex method to make a simple list in python.
x2 = 
for x3 in range(10):
## >>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Both X and X2 generate the same output!
We will focus on the Easy method known as “List comprehension”
Notice we are using a different letter in the list comprehension code below.
When learning python, a lot of example code has “words” which can be changed to letters. Like below, I’m using a “y”… Later in this tutorial or lesson… I’m going to keep changing the “y”, which is the results of the list comprehension in python below!
y = [i for i in range(11)]
You may be thinking, okay, we are increasing the numbers each time, and changing the letter in the beginning. That’s true, it’s a nice little pyramid if you run every bit of code together, which is pretty cool to know… You might be copy pasting different pieces of the code, and in this particular chunk of code, you can run the entire set of code, and not need to worry about anything! It will give you a results of our list comprehension code, which is clearly marked as “print” “firstletter”… easy enough to keep up with.. here’s a curve ball, I changed i to meow, and that works too.
z = [meow for meow in range(12)]
This list comprehension code below has more than a letter, similar to the complex list generation code above, we used x2 (example 2), and similarly, we are not using a letter to describe the results of the list comprehension. For the new programmers -> Light bulb moment? You can name the “X”, “Y”, “Z” anything you damn please… If you’re following here, you should now see a pattern, and easy pattern to generate simple lists with a range of #’s. Also, you might be seeing a little bit of math. How exciting! You’re doing math, in python!
tyler = [i for i in range(14-1)]
In the list comprehension below, I’m simply demonstrating addition… On the range() portion of the code.
tyler2 = [DOG for DOG in range(12+2)]
More math, yes division, multiplication, subtraction and addition work in python, pretty well too..
I tested, it’s accurate.
tyler3 = [i for i in range(14/2+7+1)]
The next few tutorials on list comprehensions will be right up your alley, if you understand the techie mumbo jumbo this will be a good refresh and a hilarious chunk of code you can likely help optimize, and I will gladly add anyone in the tutorial blog posts – and link to whatever website, github profile, etc, and help you rank better. As a novice at all things python, I’m excited to get to know you more as you take the journey I once took. I’m excited to get to know people who think this is total trash too. I need that kind of feedback. I’m learning every day, coding is hard, and I only know what I know, and that means if someone could show me all the ways the code works, I will master the code, otherwise I’m MR. Trial and error. so longest story short, you’re here to learn, me too, so let’s get started by learning everything there is to know about list comprehensions.
Python list comprehensions is as necessary as eating this shaved ice desert.
List comprehensions are powerful but poorly explained by the current top two ranking websites. That’s because they are…
the company website – very smart stuff
some random blog with affiliate links and viruses, popup ads..
I’m excited to show you a proper list comprehensions tutorial, without a single pop up, google ad, or affiliate link.
Some may call this an “i for i” + “python” on google!
Why is Tyler Garrett rebuilding the wiki on List comprehensions?
The current content when googling i for i python or list comprehensions, is currently plundered with garbage water.
Automate generating a list of values using python 2.X
List comprehensions 101…
If you are new, eager to learn quickly, want to learn without having to code, need lots of examples… Looking for a lot of sample code, that tests a lot of different variations of list comprehensions, or maybe… You looked online, didn’t find anything decent, a little upset trying to learn python, need a better guide… Maybe it’s just me.
Cool, that’s why I write, to replace the TRASH WATER blogs online. No monetizing, no click ads, just solutions.
Below is a quick tutorial on using a type of “find and replace” across a CSV file or you could do this find and replace on a TXT file too. I’m not a developer, just another blogger, blogging about learning python. I’m building use cases that are similar to a typical business analyst or data analyst.
You get a CSV file or TEXT file and want to scrape over the entire file, and output it with your modifications. Find and replace is the term I would think you would google if you wanted to do a find and replace in python over a CSV.
Python, without any downloaded libraries, will do a find and replace on the data above. You can copy and paste the data above into a .txt file, and change the extension to .csv — if you don’t have an excel software on your computer, or you can use Google sheets and make your own data problem.
Our goal is to clean the 3.
The 3 in the https://tylergarr3tt.com link because it’s not accurate.
For whatever reason this is going to be used by a developer and they are asking me to find and replace the “errors.” Errors in the sample data generate a use case to learn how to do a find and replace on a CSV file, which taught me that using the a previous “text file” tutorial, I was able to handle the same ETL like solution, with simple python code, and no odd libraries to be imported.
Our use case will generate a full “find and replace python solution” and a few more obvious data issues. We will remove “3” and replace it with “e” in python below, to help us move down a path of learning and solving your use case today.
The code to find and replace anything on a CSV using python
text = open("input.csv", "r")
text = ''.join([i for i in text]) \
x = open("output.csv","w")
We are not using any “imports” because this is all native python capability.
text = ''.join([i for i in text]) \
Allows you to “find and replace” using one line of code.
It looks like 2 lines of code because python lets you put a space and a “\” in front of a long line of code. The space + “\” lets me see what I’m doing easier that writing one wrapping line of code.
An example that may require a “ \” in front of your code, looks something like…because it’s easier to read.
Above image of code is an exaggeration to show you that python lets you break up your find and replace or you can do it in one line. I do it because I would go absolutely crazy if it wasn’t for that little feature, so if you’re like me, woop woop. This is a big help, otherwise
→write it like this…
text = ''.join([i for i in text]).replace("3", "e")
Above code lets us quickly replace “3”’s with “e”’s and lets us heal our link column in the csv file. Find and replace may require a more granular approach which will be covered in another lesson.
Final code to find and replace text in a CSV with python
Find and replace text or letters in a csv with python is simple, super fast, faster than any SQL stuff I’ve played with in the past, so — if you need to bulk process a CSV or TEXT file — python is a great direction because it’s easy to understand.
text = open("input.csv", "r")
text = ''.join([i for i in text]).replace("3", "e")
x = open("output.csv","w")
‘’.join is cool because it allows you to add anything, to each row of data.
Can you choose different public data sources quickly, efficiently, and use that data for data science too? Finding correlations in public data sources used to be a lot of work to wrangle.
What I said above, for most, would require multiple people.
Data architect – helps you architect your data
Database admin – helps you access your data
Data scientist – helps you with predictive analytics
Developer – migrates data science models into code
BI Developer – helps you build a dashboard
Finding Correlations in Public Data Sources is like finding the right VM in Silicon Valley.
In the time it would take for me to email all five people above, I can do all the work in Alteryx, and that’s why I love working at Alteryx.
We intend to find correlations in public data sources.
Finding correlations in public data sources is a lot like finding a pattern on your wallpaper.
Our prediction is that ethnicity, deaths, births, birth fertility, homelessness, and dozens of more measures will offer insights into average survey scores.
Finding data sources online can take time, below we offer a few great resources. Artwork found here.
The more our measures correlate, the better we can predict our future.
Remember before reading the findings that statistics are opinionated. Correlation does not mean causation.
Noticing trends in our data sources.
Here’s a scatter plot displaying HCA survey average scores per state and Total Homelessness in 2014. The points on the graph are individual states. You will notice a negative trend sloping down as the survey scores increase, the amount of homeless people decreases too.
Finding correlations in public data sources on a laptop is possible.
Scoring correlations in our data sources.
If we score the correlation between the two values, across every state, it would enable us to determine what metrics follow a similar pattern.
With scores, we can understand what correlates the most, or does not correlate to the hospital survey scores.
There are hundreds of hospitals per state. Here’s the top ten bar chart, showing how many hospitals per state are being averaged.
Mastering Multiple Public Data Sources
If you want to bring multiple data sources together, you need to be very good at SQL, data manipulation, data architecture, and a lot of spare time in a spreadsheet if this sounds like new skills. Finding correlations is another beast.
Finding a data scientist in your office may be tricky if they are busy or not available, which generates a deep dive in learning R, Python, Statistics, or Excel martial arts.
Luckily, we Alteryx our data, which means we can do all the complex SQL, data manipulation, data architecture, and pipe it through a data science model, in the same window.
What would have taken my group multiple weeks of constant work, only took us 1.5 hours!
Looking for a public data source?
Know that picking a public data source has become readily available in the past few years, and being able to quickly identify powerful data sources has become a distinguishable skill to master.
If you are interested in picking up this skill, read our solution below.
I stumbled on this request in a team project last week!
“Everyone, pick multiple data sources…”
This can sound like an easy request…
Where do you get your data?
What data is accurate?
What source of data can we trust?
What decisions are we attempting to make?
We want to find data sources that will add value to our audience, their questions will have answers, and their next steps will be clear.
In this blog, you will learn how…
You will learn how our team quickly accomplished our project using one simple whiteboarding methodology.
You’re probably thinking, ‘Yes, of course, I can pick a data source, I’m passionate about x, y, z.’
The more you grow in the data industry, the more you realize every new data source comes with new hurdles or barriers to entry.
Is the data clean? Is the data usable? Do we have access to the data?
You begin applying padding around your work, based on previous experiences, and avoid painful experiences.
If you choose to read this entirely, you will be armed with a solution to any brainstorming meeting, and you will learn where we found 3 different data sources online.
That’s right, I’m talking about your future in data.
Eventually, you’re going to hit that ten-year threshold. A decade of database-related solutions.
When you hit ten years, you start to become scared of ‘lots of disparate data sources,’ and learn to avoid these workloads.
When your meeting is going great… Get ready for that meeting to slow down.
Someone is around the corner to suggest another table of data…
The data source will put the brakes on your progress. A new data source that has never been cleaned, prepped, approved… Major ‘nope’ in my line of work…
You were asked, “What data source do you want to use?”
Feel free to play along, mentally put yourself in a group setting, and give yourself a few minutes to pick multiple data sources to present in front of a class of 40 professional peers.
You will be building decisions out of these data sources. Graphs, pie charts, forecasting, insights, etc.
Lastly, work as a team to generate a data solution surrounding these data sources. While you’re at it, don’t get too involved in figuring out what answers you will gain from your data source.
We were tasked to generate a project to kick-start our success stories. In this process, it seemed really challenging to decide on what to choose.
It was interesting because even though we were all eager to get started… We struggled to find the right granularity.
You have access to making documents aka superpowers!
Data lakes, big data, data warehouses, … Each row of data offers a granularity.
Are we looking for an address? Zip code? State? Country?
Stating different parent and child relationships are all great and good. But until these words hit a piece of paper, Google Slides, or a whiteboard… We are left remembering what was said and making decisions based on our memory.
A zip code would be a more granular view of your data than State…
But without documenting our decisions, how do we collectively come together to suggest a path forward?
Also, why am I talking about documents?
Well – documentation is really helpful and it’s tangible information you can point at and say, “LOOK”… and in return, you will likely receive feedback.
Finding multiple data sources in any single industry can feel like a daunting task.
When you’re actively finding multiple public data sources – there are a lot of options.
Noticed we just said “public data sources”…
Yes, as opposed to a private data source! If you’re new in the data industry, let me dive in.
Public data source – safe to download, safe to share, available for everyone.
Private data source – not safe to download, not safe to share, not available for everyone.
Here are a few up and coming data source providers. These are public data sets and available to everyone.
Here’s my ‘buyer beware.’ Or maybe we should say ‘extracter beware.’
Anyone can add a data source, anyone can change the data source, and Wiki’s are public – anyone can make an edit. That’s why teachers recommend we avoid using them in scholarly reports because some random person likely added that information on the Wiki.
How did our team pick a data source?
Originally, we struggled to find a data source because we were not documenting our ideas.
Our ideas were lost as soon as we said “anything” out loud.
We would say a great idea, agree it was a great idea, but failed to generate next steps.
What made a difference was documenting our brainstorming session on the dry erase board.
Having everything on the whiteboard allowed everyone to see what was being said.
Not sure how to get started whiteboarding?
Whiteboarding is usually as simple as making a word cloud and circling good items and drawing a line through bad items.
The table below demonstrates Pearson Correlation value and ap-value, to determine its statistical relevance. The smaller the p-value, the more significant our data becomes.
We are using Pearson Correlation to compare the HCAHPS hospital survey data against different ways to categorize the count of homeless people per state. Sheltered Homeless Individuals and Sheltered Unaccompanied Youth are the most statistically relevant.
Using HCAHPS Hospital Survey Data from Medicare.gov was the beginning of a group project. And a quick hypothesis that if your hospital gets bad survey scores, it’s likely because there are other outliers that correlate.
HCAHPS Survey data gives us quick insights into many different values but to do a quick analysis, we want to stick with an average of the values, and the data offers an average, per hospital.
Thousands of people take a survey or submit a survey.
The average of those values shown in the HCAHPS Hospital Survey Data.
A score from 1 to 5.
1 being the worst and 5 being the best score.
Hopefully, your hospital has a decent score!
Dave Chappelle laughing about hospital survey data
There are hundreds of hospitals in the HCAHPS Survey Data.
When looking at the website above, it’s important to understand how many hospitals per state, to understand the sample size at a state level.
The bar chart below is a distinct count of hospitals per state.
HCAHPS Hospital Survey Data – the number of hospitals per state. In Tableau Desktop by Tyler Garrett.
HCAHPS Hospital Survey Data has many Correlations
HCAHPS Hospital Survey Data has a lot of negative correlations, from a Pearson correlation perspective. In my studies of this data, it was easy to see several correlating factors that supported my initial hypothesis.
If you have bad survey scores,…
It’s likely you also have a high population of homeless people, high death rates, low fertility rates, and also Census 2010 households ethnicity aggregations will more than likely tell a story too.
Finding a Correlation is not Finding Causation.
Just because your state loses the test – remember its an average per state. Correlation is not causation.
Yes, this data can tell you the worst hospitals in your state. It’s important to note; correlation is not causation and it’s important to talk about these potentially predictive outliers.
Follow the link above and start analyzing other data related to the medical field or read more about the metadata below.
Usually, I would leave that data solution here but today I’m a little past that and will be blogging more about the correlations, and try to find statistical relevance in these measured values.
More about HCAHPS Hospital Survey Data
HCAHPS Hospital Survey data has a little bit of metadata too.
As of May 19, 2018, HCAHPS Hospital Survey Data has been over 20,000 downloads and over 166,000 views.
The row count is a staggering 266,000 rows by 23 columns. Learn more about this dataset here. It’s a list of hospital ratings for the Hospital Consumer Assessment of Healthcare Providers and Systems (HCAHPS). HCAHPS is a national, standardized survey of hospital patients about their experiences during a recent inpatient hospital stay.
Hello readers, yay a blog post. A new post on a new domain.
Welcome to TylerGarrett.com and thanks for reading my first new post on a new domain. TylerGarrett.com is a free resource and a personal blog founded by Tyler.
A new post usually consists of a little context about what you want your blog to be about.
I believe a few topics will suffice.
Technology Demos and walkthroughs.
Growth Hacks and safe SEO tips.
Photography and free stock images.
Music, Mixes, Remixes, etc.
Using data and data visualization to discuss topics.
New posts and new domains moving forward…
My new posts will be about tech, photos, music, growth hacks, and data related to these topics.
My family saying hello from a bluebonnet field in Texas.
Guest blogs will be a place where I will beg some genius to say a few words on a topic or two.
An interview will be a similar case. I’m going to bug people I meet while traveling to answer a few questions on the fly or hopefully people will use the website to sign up for interviews and I will stop bugging strangers.
What’s your next new post going to be? [Nerd Alert]
I’ve been quietly journaling offline for the past few months, mostly technology related, as I’m learning Alteryx’s platform, and boy I’m excited about the future posts too.
Just last week I learned how to use APIs without programming and it wasn’t complex.
So hopefully I will be writing about API usage, a user-friendly guide to using APIs, and sharing the data I’m able to grab.
Next post ideas, I need an idea!
Getting idea’s for posts can come in a lot of fashions, like writing about a hotel you stayed in, taking photos, and giving it a rating.
Another idea is using an automated system to give you ideas.