Lists are a helpful and frequently used feature in Python.
And list comprehension gives you a way to create lists while writing more elegant code that is easy to read.
In this beginner-friendly article, I'll give an overview of how list comprehension works in Python. I'll also show plenty of code examples along the way.
Let's get started!
forloop to create a list in Python
One way to create a list in Python is by using a
For example, you can use the
range() function to create a list of numbers ranging from 0 - 4.
#first create an empty list my_list =  #iterate over the numbers 0 - 4 using the range() function #range(5) creates an iterable, starting from 0 up to (but not including) 5 #Use the .append() method to add the numbers 0 - 4 to my_list for num in range(5): my_list.append(num) #print my_list print(my_list) #output #[0, 1, 2, 3, 4]
What if you already have a list of numbers, but want to create a new list with their squares?
You could again use a
for loop, like so:
#initial list of numbers numbers = [1,2,3,4,5,6] #create a new,empty list to hold their squares square_numbers =  #iterate over initial list #multiply each number by itself #use .append() method, to add the square to the new list, square_numbers for num in numbers: square_numbers.append(num * num) #print new list print(square_numbers) #output #[1, 4, 9, 16, 25, 36]
But there is a quicker and more succinct way to achieve the same results – by using list comprehension.
When you're analyzing and working with lists in Python, you'll often have to manipulate, modify, or perform calculations on every single item in the list, all at once.
You may also need to create new lists from scratch, or create a new list based on the values of an already existing list.
List comprehension is a fast, short, and elegant way to create lists compared to other iterative methods, like
The general syntax for list comprehension looks like this:
new_list = [expression for variable in iterable]
Let's break it down:
expressionor operation you'd like to perform and carry out on each value inside the current iterable. The results of these calculations enter the new list.
expressionis followed by a
variableis a temporary name you want to use for each item in the current list that is going through the iteration.
inkeyword is used to loop over the iterable.
iterablecan be any Python object, such as a list, tuple, string and so on.
new_list. The old list (or other object) will remain unchanged.
ifstatement and additional
Using the same example from earlier on, here is how you'd create a new list of numbers from 0 - 4 with the
range() function in just one single line, using list comprehension:
new_list = [num for num in range(5)] print(new_list) #output #[0, 1, 2, 3, 4]
This has the same output as the
for loop example, but with significantly less code!
Let's break it down:
range()constructs a list of numbers.
inkeyword to iterate over the numbers.
forclause is a variable, a temporary name for each value in the iterable. So
numwould be equal to
0in the first iteration, then
numwould be equal to
1in the next iteration and so on, until it reached and equalled the number 4, where the iteration would stop.
forclause is an expression for each item in the sequence.
You can even perform mathematical operations on the items contained in the iterable and the result will be added to the new list:
new_list = [num * 2 for num in range(5)] print(new_list) #output #[0, 2, 4, 6, 8]
Here each number in
range(5) will be multiplied by two and the new value will be stored in the variable
What if you had a pre-existing list where you wanted to manipulate and modify each item in it? This would be similar to the example from earlier on, where we created a list of squares.
Again, you can achieve that with just one line of code, using list comprehension:
#initial list numbers = [1,2,3,4,5,6] #new list #num * num is the operation that takes place to create the squares square_numbers = [num * num for num in numbers] print(square_numbers) #output [1, 4, 9, 16, 25, 36]
Optionally, you can use an
if statement with a list comprehension.
The general syntax looks like this:
new_list = [expression for variable in iterable if condition == True]
Conditionals act as a filter and add an extra check for additional precision and customisation when creating a new list.
This means that the value in the expression has to meet certain criteria and a certain condition you speficy, in order to go in the new list.
new_list = [num for num in range(50) if num % 2 == 0] print(new_list) #output #[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]
In the example above, only the values where the condition
num % 2 == 0 is checked and evaluates to True will enter
The modulo operator is used on every single one of the numbers in the sequence of numbers starting from 0 and ending in 49.
If the remainder of the numbers when divided by 2 is 0, then and only then does it enter the list.
So in this case, it creates a list of only even numbers.
You can then make it as specific as you want.
For example, you could add more than one condition, like so:
new_list = [num for num in range(50) if num > 20 and num % 2 == 0] print(new_list) #output #[22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48]
In this example, there are two conditions
num > 20 and
num % 2 == 0.
and operator indicates that both have to be met in order for the value to be added to the new list.
The values that don't meet the conditions are excluded and are not added.
You can create a new list with the individual characters contained in a given string.
fave_language_chars = [letter for letter in "Python"] print(fave_language_chars) #output #['P', 'y', 't', 'h', 'o', 'n']
The new list that gets created is comprised of all the separate letters contained in the string "Python", which acts as an iterable.
Just like numbers, you can perform operations on the characters contained in a string and customize them depending on how you want them to be in the new list you create.
If you wanted all letters to be uppercase, you would do the following:
fave_language_chars_upper = [letter.upper() for letter in "Python"] print(fave_language_chars_upper) #output #['P', 'Y', 'T', 'H', 'O', 'N']
Here you use the
.upper() method to convert every single letter in "Python" to uppercase and add them to the
The same goes if you wanted all your letters to be lowercase - you'd instead use the
And there you have it! You now know the basics of list comprehension in Python.
It offers an elegant and concise syntax for creating new lists based on existing lists or other iterables.
Original article source at https://www.freecodecamp.org
Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.
#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
List comprehension is used for creating lists based on iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops.
The syntax of a list comprehension is actually easy to understand. However, when it comes to complex and nested operations, it might get a little tricky to figure out how to structure a list comprehension.
In such cases, writing the loop version first makes it easier to write the code for the list comprehension. We will go over several examples that demonstrate how to convert a loop-wise syntax to a list comprehension.
Basic structure of list comprehension (image by author)
Let’s start with a simple example. We have a list of 5 integers and want to create a list that contains the squares of each item. Following is the for loop that performs this operation.
lst_a = [1, 2, 3, 4, 5] lst_b =  for i in lst_a: lst_b.append(i**2) print(lst_b) [1, 4, 9, 16, 25]
#python #programming #how to convert loops to list comprehension in python #convert loops #list comprehension #how to convert loops to list comprehension
No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas.
By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities.
Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly.
Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.
Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions.
Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events.
Simple to read and compose
Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building.
The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties.
Utilized by the best
Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player.
Massive community support
Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions.
Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking.
Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.
The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.
Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential.
The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.
#python development services #python development company #python app development #python development #python in web development #python software development
List comprehension is nothing but a shorter and crisper version of the code and also memory efficient. By using this we can either create a new list or perform some operation in an existing list.
The normal code for creating a list of 0–9 will be like
x= for i in range (10): x.append(i) print(x) [0,1,2,3,4,5,6,7,8,9]
By using list comprehension
x=[i for i in range(10)] print(x) [0,1,2,3,4,5,6,7,8,9]
As you can see the normal code is long but the code that we did using list comprehension does the job just in one line so list comprehension is preferred over the traditional method.
#list-comprehension #lists #python #python-list-comprehension