List in Python and it’s Examples

2
5872
List in python

Introduction to lists

A list in Python is a data structure that acts as a container to store multiple values. A python list is an ordered sequence of values and is mutable i.e. we can add values to a list, delete values and add new values. Thus, a list in Python can grow and shrink in size. Each value in a list is called as an element or a list item or simply an item.
A real-life example would be a shopping list that you make before heading out for shopping so that you don’t forget what you have to buy. You add items to that shopping list and you may strike off items from the list if you change your mind about buying that item or you may replace an item with another item. Thus, a list in python is pretty much like a shopping list that lets you add items to it, delete items from it, or replace existing items by other items.

Creating a list in Python

List in Python is created by enclosing the list items within square brackets with the individual items separated by commas. For example, you want to create a list to store the first five even natural numbers.
Even= [2,4,6,8,10]. Here [2,4,6,8,10] are the list items of the list named Even.
Similarly, if you want to create a list of fruits then,
fruits= [‘apples’, ‘oranges’, ‘bananas’, ‘mangoes’]
Here observe that the items of the list Even are all integers whereas the items of the list fruits are all string values.

Types of Lists

Lists can be broadly classified into two types based on the type of values they hold.

⦁ Homogeneous list:

A list in which all the items belong to the same data type i.e. all the items are either integer or all float or all string. The lists Even and fruits are examples of the homogenous list.

Non-Homogeneous list

A list in which the items belong to different data types. e.g. employee= [‘John’, 22, ‘Sales’, 20000]
Here the list employee has two integer items and two string items and hence it is a non-homogenous list.

Accessing the items of list in Python

Consider the previously created list fruits= [‘apples’, ‘oranges’, ‘bananas’, ‘mangoes’]
Now we want to access the elements of the list. We can access an element of a list by the index of that element.
For e.g. print(fruits[0])
Output: apples
print(fruits[1])
Output: oranges
Thus, 0 and 1 are the indices of the elements ‘apples’ and ‘oranges’ respectively.
Indexing in a python list starts from 0. This means that,
Index of 1st element= 0
Index of 2nd element= 1
Index of 3rd element= 2
.
.
.
Index of nth element= n-1
Once again consider the example of the list of the fruits

ElementIndexNegative index
Apples0-4
Oranges1-3
Bananas2-2
Mangoes3-1

Thus, if we want to access the last element of an array then we can access it by the index -1.

>>print(fruits[-1]).
Output: mangoes
Similarly, the second last element of an array can be accessed by the index -2


>>print(fruits[-2])
Output: bananas
Now, we want to access or print a specific range of elements of the list. This can be achieved by performing the slicing operations on the list. For this, we have to provide the ‘start’ index and the ‘stop’ index separated by a colon and the elements between the start index and the stop index will be printed, excluding the stop index element.

fruits=['apples','oranges','bananas','mangoes','grapes','strawberry']
 print(fruits[1:4])

Output:

['oranges', 'bananas', 'mangoes']

Here, 1 is the start index and 4 is the stop index. Thus, all the elements with indices ranging between 1 and 4, excluding 4 have been printed. We got all the list items with indices 1 to 3.

For Example 2
If we don’t specify the stop index, then, all the elements from the start index until the last element of the list are printed.

fruits=['apples','oranges','bananas','mangoes','grapes','strawberry']
 print(fruits[1:])

Output:

['oranges','bananas','mangoes','grapes','strawberry']

For Example 3
Similarly, if we don’t specify the start index, all the elements from the beginning of the list until the stop index are printed.

fruits=['apples','oranges','bananas','mangoes','grapes','strawberry']
 print(fruits[::-1])

Output:

['strawberry','oranges','bananas','mangoes','grapes','apples']



Widget not in any sidebars

Nested lists in Python

A nested list is a list whose items are lists themselves. The inner lists are called as sub-lists
For Example

nested=[[1,3,5],[2,4,6]]
 print(nested[0])

Output:

[1, 3, 5]

In the above example, we created a nested list by the name nested. Observe that the list has two elements which are themselves lists.
Thus, nested[0] prints the first element of the nested list i.e. the list [1,3,5]

Now, if we want to access the elements of the inner lists then we do so by adding another set of square brackets. Here’s how:

nested=[[1,3,5],[2,4,6]]
 print(nested[0][2])

Output:

5

Thus, the first square bracket gives access to the complete inner list (sub-lists) and the second square bracket gives access to the elements of the inner list..

There’s no limit to the level of nesting.


Concatenation

You can concatenate two or more lists using the ‘+’ operator.
For example,

list1=[1,3,5,7]
 list2=[2,4,6,8]
 list3=['odd','even']
 print(list1+list2+list3)

Output:

[1, 3, 5, 7, 2, 4, 6, 8, 'odd', 'even']

Thus, in the above example we created three lists and using the + operator we concatenated them and obtained a single list.


List methods and functions in Python

The list datatype has many in-built methods and functions that make manipulating the lists and accessing them very simple.

Functions

Some of the most common built-in functions that are used with lists are:
len( ): This function returns the length or size of the list i.e. if the list has 7 items then the len( ) functions return the integer value 7.

For Example

fruits=['apples','oranges','bananas','mangoes','grapes','strawberry']
 print('The no, of fruits in the basket are:',len(fruits))

Output:

The no, of fruits in the basket are: 6

min( ): This function returns the item with the minimum value in the list.

For Example

list1=[B,C,D,A]
 list2=[11,22,33,44]
 list3=[2.3,7.8,22.9,1.6]
 print(min(list1))
 print(min(list2))
 print(min(list3))

Output:

A
 11
 1.6

max( ): this function returns the item with the maximum value in the list.

For Example

list1=[B,C,D,A]
 list2=[11,22,33,44]
 list3=[2.3,7.8,22.9,1.6]
 print(max(list1))
 print(max(list2))
 print(max(list3))

Output:

D
 44
 22.9

all( ): Returns true if all element are true (non-zero)or if list is empty. If any element of the list is zero then, it returns false.

For Example

list1=[1,2,3,4]
 list2=[]
 list3=[0,2,4,6]
 print(all(list1))
 print(all(list2))
 print(all(list3))

Output:

True
 True
 False

any( ): This function returns true if any element of the list is true(non-zero). if list is empty, return false.

For Example

list1=[1,2,3,4]
 list2=[]
 list3=[0,2,4,6]
 print(any(list1))
 print(any(list2))
 print(any(list3))

Output:

True
 False
 True

enumerate( ): This function helps keep count of iterations by adding a counter to an iterable and returns it in a form of enumerate object.

For Example

demo=['I','Love','Python']
 enum=enumerate=(demo)
 print(list(enum))
 print(type(enum))

Output:

[(0, 'I'), (1, 'Love'), (2, 'Python')]
 <class, enumerate>

Methods

The list data type has the following functions:
list.append( x ): This method appends an element or an object to a list i.e. adds an item to the end of a list. The value to be added can be a numeric value or string or can be another list.

For Example

fruits=['Apple','Banana','Orange']
 fruits.append('Strawberry')
 print(friuts)
 more_fruits=['Mangoes','Grapes']
 fruits.append(more_fruites)
 print(fruits)

Output:

['Apple', 'Banana', 'Orange', 'Strawberry']
 ['Apple', 'Banana', 'Orange', 'Strawberry', ['Mangoes', 'Grapes']]

Let’s take another example: We can use the for loop for appending items of a list to another list in the following way

emp1=[22,'John','SALES']
 emp2=[24,'Peter','ACCOUNTS']
 for i in emp2:
   emp1.append(i)
 print(emp1)

Output:

[22, 'John', 'SALES', 24, 'Peter', 'ACCOUNTS']

list.insert(i,x): This method inserts an element in a list at a specified index. The first argument ‘i’ is the index at which the element is to be inserted and the second argument is the item to be inserted.

For Example

emp1=[22,'John','SALES']
 emp1.insert(2,25000)
 print(emp1)

Output:

[22, 'John', 25000, 'SALES']

list.remove(i,x): This method removes the element ‘x’ from the list.

For Example

fruits=['Apple','Banana','Orange','Mangoes']
 fruits.remove('Apple')
 print(fruits)

Output:

['Banana','Orange','Mangoes']

list.pop(i): This method removes the item from the specified position. Thus, it takes an index as the argument. If no argument is specified, then it removes the last element from the list.

For Example

fruits=['Apple','Bananas','Oranges','Mangoes']
 fruits.pop(0)
 print(fruits)
 fruits.pop()
 print(fruits)

Output:

['Bananas','Oranges','Mangoes']
['Bananas','Oranges']

list.reverse( ):This method reverses the elements of the list in place.

For Example

fruits=['Apple','Bananas','Oranges','Mangoes']
 fruits.reverse()
 print(fruits)

Output:

['Mangoes', 'Oranges', 'Bananas', 'Apple']

list.count(x): This method returns the number of times an item occurs in the list. It takes one argument ‘x’ whose no. of occurrences we want to find.

For Example

demo=[11,16,18,20,11,84,11]
 demo.count(11)

Output:

3

list.clear( ): This function removes all the items from the list. Thus, the list gets converted to an empty list.

For Example

demo=[2,3,4,5,6]
 demo.clear()
 print(demo)

Output:

[]

list.index(x): This method returns a zero-based index in the list of the first item whose value is equal to x. Raises a Value error  if there is no such item in the list.

For Example

emp1=[22,'John',40000,'SALES']
 emp1.index(40000)

Output

2

list.sort(reverse=False): This method sorts items in a list in ascending order. The method has the optional argument reverse. If reverse=True, then the method sorts the list items in descending order.

For Example

demo_list=[21,34,11,76,2,99]
 demo_list.sort()
 print(demo_list)
 demo_list.sort(reverse=true)
 print(demo_list)

Output:

[2, 11, 21, 34, 76, 99]
[99, 76, 34, 21, 11, 2]

list.extend(x): This method appends the contents of a sequence ‘x’ to the list.

For Example

emp1=[22,'John',40000,'Sales]
 emp2=[24,'Peter',30000,'Accounts']
 emp1.extend(emp2)
 print(emp1)

Widget not in any sidebars

Output:

[22, 'John', 40000, 'Sales', 24, 'Peter', 30000, 'Accounts']

So, the above discussed are some of the most important methods and functions for list creation and manipulation.

2 COMMENTS

  1. […] Lists are similar to arrays in C. However; the list can contain data of various types. The items stored in the list are separated with a comma (,) and enclosed within square brackets []. We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were working with the strings. […]

LEAVE A REPLY

Please enter your comment!
Please enter your name here