The List is one of the versatile collection Data Types in Python. It is similar to an array but stores multiple type data in a single variable.
We have discussed on the List and other collection types in our earlier blogs. We recommend our readers to go through this collection details from below link blog.
Python_Basics
In this blog, we will learn the collection “List” and “List comprehension“ in Python in more detail.
The List is a collection of Data which is ordered, means its index are fixed and is mutable, i.e, items inside a list can be changed at any point of time.
The items inside a list are separated by ‘,’ and are enclosed within ‘[ ]’.
Eg: list1 = [ 1, 14, 8, 3, 23]
list2 = [ “Red”, “Yellow”, “Green”, “Blue”]
We can perform numerous operations on the list. Let us understand each operation with an example.
ACCESSING ITEMS FROM A LIST
We can access items from a list by referring to its index number. Indexing of a list starts from 0 to (length-1).
To print the first and last item of a string.

CHANGING LIST ITEM VALUE
Since items are mutable, we can change the value of any of the items as:

INSERTING ITEMS TO A LIST
We can insert new items in an existing list with the help of append() and insert() method.
The difference between the two methods is append() method adds an item at the end of the list and insert() method adds an item at a specified index.

DELETING ITEMS FROM A LIST
We can delete item/s from a list by a number of methods like pop(), clear(), remove() and ‘del’ keyword.
pop() method removes the last item of a list or at the specified index.
clear() method empties the list.
remove() method removes the specified item.
The del keyword removes an item at a specified index or deletes the list completely.

LENGTH OF LIST
We can determine the length of the element, i.e., the number of items in a list by len() method.

LIST SLICING
List slicing is the method of splitting a list into its subset. We do this with the help of the indices of the list items.

During slicing when we specify two index, the last indexed item (n) is usually excluded and item at (n-1)th position is taken.
LOOPING THROUGH A LIST
When we have a number of items in a list, we can loop through the list with the help of ‘for’ loop as shown below:

Another example of list looping where we have added 5 to each element in the list.

LIST COMPREHENSION
List comprehensions are Python functions that are used to create new lists, sets, dictionaries, etc.using lists that have already been created.
It reduces loops and makes code easier to read.
As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.
The comprehension is usually shorter, more readable, and more efficient.
Types of comprehension:
- List
[ i*2 for i in range(3) ]
- Set
{ i*2 for i in range(3)}
- Dictionary
d = {key: value for item in sequence …} </n>
{ i: i*2 for i in range(3)}
We will understand the concept of List Comprehension in a better way by below a number of examples.
1. Squaring values of a list and a set
In the above program, we have created a function with name ‘square’ and passed a variable ‘list’ as the argument. Then we implemented list comprehension to square each value of the list. And then we defined the list to be in the range 0 to 10 as the last range value is excluded. Therefore the output would be like:

In the above program, a set of values is stored in a variable called ‘setvalue’ from 0 to 5. We implemented list comprehension to square each value in the setvalue and stored it in variable ‘square’. To know the collection type of ‘square’ we can check it by using type(square) in our code. Therefore the output would be something like this.

2. Converting temperature from Centigrade to Fahrenheit.

3. Working with Strings
Given is a string containing the names of people both first and last name. We will be performing two operations on the list, first to separate only the last name and second to print the name in reverse order.
The above operations will be carried out by using the split() method.
split() method returns a list of strings after breaking the given string by the specified separator (i.e., by which the list is separated).
syntax: str.split(delimeter)
It returns a list of strings after breaking the given string by the specified separator.


4. Printing cubes of first 10 natural numbers
In the above program, we have created a function named cube and passed a variable list as the argument. Then list comprehension is implemented where for each value in the list its cube is calculated. The range for the list is given from 0 to 10 where 10 being excluded.
Therefore the output would be:

5. Finding common words in 2 lists

6. List Comprehension to get the given output
l1=[1,2,3,4,5]
l2=[4,5,6,7]
- output 1 : [1,2,3]
- output 2 : [6,7]
- output 3 : [4,5]



7. Summing the numbers when two dice are rolled
Note: the sum of two numbers in tuples should be more than 7.

8. For given input , produce given output
inp = “Hello Python World”
- output 1 : ‘dlroW nohtyP olleH’
- output 2 : ‘olleH nohtyP dlroW’
- output 3 : ‘World Python Hello’

The join() method is a string method and returns a string in which the elements of the sequence have been joined by str separator.


9. Removing vowels from list

10.Replacing missing spaces in a string with the least frequent character
- Input : ‘dbc deb abed gade’
- Output: ‘dbccdebcabedcgade’




11. Create a numpy 4*4 array and get the given output
- Input: array([ [ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15] ]) - Output = array([ [ 4, 6],
[12, 14] ])


12. Creating a DataFrame and performing operations on it
In this example, we will be creating and Data Frame and check for some given condition.
In the above code, we have imported the Pandas library and created a DataFrame with three columns viz, DateOfBirth, Name, and State. Therefore the output will be:

Now we have to find all rows in the above DataFrame where ‘Name’ contains “ane” or ‘State’=”TX”

df[‘Name’] selects the Name column of the DataFrame. df[‘Name’].str allows us to apply string methods (e.g., lower, contains) to the DataFrame.
df[‘Name’].str.contains(‘ane’) checks each element of the Column as whether it contains the string ‘ane’ as a substring. The result is a Series of Booleans indicating True or False.
df[df[‘Name’].str.contains(‘ane’)] applies the Boolean ‘mask’ to the dataframe and returns a view containing appropriate records.
This brings us to the end of the blog. Hope this blog helped you in learning List Comprehension in Python from scratch. You can refer to the blogs on Python Libraries to understand List Comprehension in a better way.
Data_Manipulation_with_NumPy
Data_Manipulation_with_Pandas
Keep visiting our website AcadGild for blogs related to Data Science and Big Data.