List Comprehensions - Python Tips and Tricks #1

NeuralNine · Beginner ·🛠️ AI Tools & Apps ·5y ago

Key Takeaways

This video covers list comprehensions in Python, providing tips and tricks for creating lists in a concise way. The tutorial is part of a series on Python tips and tricks by NeuralNine.

Full Transcript

[Music] what is going on guys welcome to this new tutorial series on neural nine it is about python tricks and tips which is essentially a tutorial series that is not for beginners not for intermediates necessarily it's just showing you some tricks that you can use in the python language uh i would not consider them to be very advanced skills or something that is very complicated but i would also say it's not necessarily a beginner topic which is why i made this extra playlist here where we're just going to talk about interesting things that you can do with python that speed up your coding make your code more fancy more effective more efficient whatever and in the first episode today we're going to start with list comprehension so let us get right into it so what list comprehensions essentially are just a concise way to create lists in python now let's say you have some sort of list here for example numbers equals and then you have a bunch of values here 18 16 22 99 23 11 54 and so on just some values and what you want to do is you want to filter out all the even values and you want to create a new list only containing the even values of this list so what you would do is you could say new list or even numbers whatever uh create an empty list and then you would go ahead and say 4 number and numbers what i'm going to do is i'm going to say okay if the number is even so if the division by the number two results in a remainder of zero um then i'm just going to say new list dot append the number that we're talking about so this is a way that definitely works so we can go ahead and say print new list and you will see that we'll end up with a list only containing the even values down here you can see 18 16 22 and 54. we don't have any other even values in the list um and this is not a wrong way it's not an inefficient way but it takes more lines of code than if we use list comprehensions now list comprehensions are very very simple to use instead of writing a full loop and then an if statement across multiple lies lines what we do is we use the square brackets and inside of those square brackets we specify what the list shall contain so i can say for example it shall contain the number so just the number that we're talking about i haven't defined what the number is yet i'm just saying the number for all the number uh elements in numbers so in this case what i'm doing is i'm saying the element that ends up in the list is the first thing that i say here so number but what is number so i can also call this x for example what is x x is just every element in numbers and now what i can do is i can add a condition to it so i can say x for x in numbers but only if x modulus 2 equals 0. so this is a one-liner here as you can see new lease new list equals x for x in numbers if x modulus 2 equals 0. that is the only condition and if i go ahead and print this here you will see that we'll end up with the exact same result in the terminal down here 18 16 22 and 54 because the code is essentially the same it's just written in a different way in a more concise way using list comprehensions now another thing that we can do inside of those list comprehensions is not only manipulate the condition and the loop we can also manipulate the actual object that we're adding into the list so let's say we have numbers here again but this time we have one two three four five six seven and what i want to do is i don't want to add those values to the list i want to add uh powers of two to the list so i'm going to say powers of two and what i want to do is i want to take 2 to the power of 1 2 to the power of 2 2 to the power 3 and so on and get it into the list so what i can do here is i can not only say x for x in numbers i can also say 2 to the power of x for x in numbers and the important thing is here i'm not only able to manipulate what i'm iterating over or what the condition is so i can of course also specify an if statement here but i can also manipulate the element itself i don't have to work with x uh directly i can use x just as in as an exponent for two so i can say 2 to the power of x here and what i'm ending up with at the end is just the powers of 2 which we can see when we run the script you can see i end up with 2 4 8 16 32 64 128 because those are the powers of two and of course i can also get rid of this list here and just replace it with range uh whatever for example 30 and i'll get all the powers of two up until 30. so up until the exponent of 30 1 2 4 and so on until we get to this large number here 2 to the power 30 or 2 to the power of 29 not sure where it stops but you can specify any kind of list at the end here and then you can just go ahead iterate through it and then apply an operation to the result you don't have to store x directly based on a certain condition you can also go ahead and say 2 to the power of x or do anything you want with x you can also apply a function that returns another value and of course i can add an if condition here as well so i can say if x is divisible by five for example if i want to do that and i'll only get two to the power of numbers that are divisible by five as you can see so last but not least we're going to look at an example that will show you that you can also use else branches not only if statements and conditions that have to be met but also what happens if they're not met and for this i prepared a list of words a list of string strings and what we have here is the word automobile we have the word car we have the word anger we have the word fox and we have the word anchor and the idea is or the trivial task here is to just get all the words that start with a and to make them uppercase while all the other words remain lowercase so of course we can do this in many different ways we can do this with a map function which is not a trick that we're going to learn about we can do this with an ordinary loop but we can also do this with a list comprehension so what we can do here is we can just say words equals and then we can say word dot upper so we're saying the word shall be upper if the word dot starts with which is a string function with the letter a and else we can say word so in this case we're using a so-called ternary operator i'm going to make in a separate video on this one but essentially we're using this concise if statement here we say okay if this condition in the middle is met we're going to do this here and if it's not met we're going to just use the word uh and we're going to do this thing for all the words in words so as you can see we're saying word dot upper if word starts with a else just the ordinary word for every word in words and i think we could also add a condition to the end here uh but it's not necessary right now so what we can do here is we can just go ahead and print words and you're going to see that automobile anger and anchor are now uppercase because they satisfy the condition where it starts with a and car and fox remain the same now of course if i don't use this else thing here if i just say uh word.upper if word starts with a at the end for example here um i will only get the words that start with a of course they're going to be uppercase but i'm losing carr and fox because i don't have an alternative of what to do if the word does not start with a so this is also one thing we can do with list comprehensions so that's it for today's video hope you enjoyed and hope you learned something if so let me know by hitting the like button and leaving a comment in the comment section down below let me know if you like this tutorial series if you like this kind of video um if so i'm going to make much more of it because it's a very uh simple tutorial playlist you know you just have to find something in python that's exciting and you can make a video about it it's not too complicated you don't have to understand uh machine learning mathematics or any complex things you can just go ahead and find a nice feature of the language and then use it so if you want to see more of those videos let me know in the comment section based on your response i'm going to decide if i'm going to make just a couple more videos or a lot more videos so let me know in the comment section and by hitting the like button also make sure to subscribe to this channel if you want to see more future videos for free other than that thank you very much for watching sooner next video and bye [Music]

Original Description

This new tutorial series is about tips and tricks for the Python language. Some of the things will be fancy and beautiful and others will be very useful and efficient. In this first episode we talk about list comprehensions, which are a concise way to create lists in Python. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🖥️ My Coding Setup 🖥️ ⌨️ Keyboard: http://hyperurl.co/neuralkeyboard 🖱️ Mouse: http://hyperurl.co/neuralmouse 🖥️ Monitor: http://hyperurl.co/neuralmonitor 🎙️ Microphone: http://hyperurl.co/neuralmicrophone ✏️ Drawing Tablet: http://hyperurl.co/neuraldraw 🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches list comprehensions in Python, providing a concise way to create lists. It's part of a tutorial series on Python tips and tricks by NeuralNine. By watching this video, you'll learn how to write more efficient Python code.

Key Takeaways
  1. Import necessary Python modules
  2. Define a list comprehension syntax
  3. Use list comprehensions to create lists
  4. Practice using list comprehensions with example code
  5. Apply list comprehensions to real-world problems
💡 List comprehensions provide a concise way to create lists in Python, making code more efficient and readable.

Related AI Lessons

I Built a Free AI-Powered YouTube SEO Toolkit With Zero Budget. Here’s What Actually Happened.
Learn how a solo dev built a free AI-powered YouTube SEO toolkit with zero budget and the lessons they learned from the experience
Medium · Startup
How to Create a Second Version of Yourself Inside Obsidian Using AI (Step-by-Step Guide)
Learn to create a second version of yourself inside Obsidian using AI with a step-by-step guide
Medium · ChatGPT
How to prepare for Spain civil service TIC exam using AI in 2026
Learn how to prepare for the Spain civil service TIC exam using AI in 2026, boosting your chances of success with technology-driven study techniques
Dev.to · David García
Going Viral! How I Created AI Kissing Videos Step by Step Easily Using AIAI.com
Create viral AI kissing videos using AIAI.com in a step-by-step process, leveraging AI technology for creative content creation
Medium · AI
Up next
Low-Tech, High-Impact: Replacing Your Receptionist With a $15 AI Phone System
Maximum Lawyer
Watch →