Python Tutorials

Python List:

Comprehension, Append, Sort, Length, Reverse EXAMPLES

What is List?

Let’s think of a list as a cargo train that is used to hold different types of goods for a specific time of period. In python lists are just like this train, it is used to store items of the same as well as a different data type.

We just stored 5 numbers in a list that can be accessed using num_list variable.

List_of_num = [1,2,3,4,5]

Different data type elements can also be stored in the list just like the above example. Let’s see

list_of_num = ['Hello',5,2.99,'World']

Accessing values within lists

We can access values stored in the list using the square brackets. Let’s have a look at the example below.

In the list “Hello” is at the 0th index, ‘5’ is at the 1st index, ‘2.99’ is at the 2nd index, ‘5’ is at the 4th index,

list_of_num = ['Hello',5,2.99,'World']

The shown below will be the output.

List Comprehension

List comprehensions are used for converting one list into another list or creating a new list from other iterables. We can achieve the same task using a simple loop structure but list comprehension provides a short syntax to obtain the same results.

Let’s take an example of finding cubes of a list of numbers. 

Here is an example of using simple loops.

numbers = [1, 2, 3, 4, 5]
cubes = []
for n in numbers:

Syntax of list comprehension

new_list = [expression for_loop_one_or_more conditions]

Let’s calculate the cubes using list comprehension.

numbers = [1, 2, 3, 4, 5]
cubes = [n**3 for n in numbers]

Using list comprehension we achieved the same task using in 3 lines instead of 5 lines.

Append function.

Append function is used to add an item at the end of python list just like adding another cabin at the end of the train. 

Let’s take a look at the example.

numbers = [1, 2, 3, 4, 5]

We can append any type of data.

numbers = [1, 2, 3, 4, 5]

Sort function

The sort function is used to sort the items in the python list in the ascending as well as descending order.

numbers = [1, 5, 2, 6, 3, 4]
numbers.sort()  # for ascending order
numbers.sort(reverse=True)  # for descending order

Length function

Length function is used to find the length of the list. Let’s take a look at an example to find out the length of the list.

numbers = [1, 5, 2, 6, 3, 4]

Reverse function

The reverse function is used to reverse the items of the list. Take a look at the example.

list_of_string = ['I', "am", "here"]

Facebook Comments

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top button