Python list, usage, examples, applications, demonstrations


Advertisements



Learn python list defining, accessing, indexing, slicing, concatenating, repeating, updating, deleting items in lists, mutability in lists, lists exercises and solutions.

Defining a list in Python

  Step 1: To begin with, Let's write a simple python program to define list and name it as list1.py as shown below. Lists are oderderd collection of arbitrary objects or data types. So you can collect different data types using a list. Lists are defined by having square brackets. Each element or value that is inside of a list is called an item. In our list1.py program list Ls contains 3 items of the string data type. List Lm contains items from mixed data type such as a string data type and number data type. List Le is an empty list where as list L4 is defined as another list with 4 items in the list and each is of number data type. List Lss is a list having another list nested in it.



#!/usr/bin/python

def main():
    Ls = ['abc','def','ghi']
    print ('printing a list with string data type')
    print (Ls)
    Lm = ['abc',1]
    print ('printing a list with string and number data type')
    print (Lm)
    Le = []
    print ('printing an empty list')
    print (Le)
    L4 = [10,11,12,13]
    print ('printing a list of 4 items')
    print (L4)
    Lss = ['str',['str1','str2']]
    print ('printing a list with nested sublist')
    print (Lss)

if __name__ == '__main__':
    main()

  Step 2: Let's compile the program we wrote in the last step. The output of the program is as shown below.

>>>
printing a list with string data type
['abc', 'def', 'ghi']
printing a list with string and number data type
['abc', 1]
printing an empty list
[]
printing a list of 4 items
[10, 11, 12, 13]
printing a list with nested sublist
['str', ['str1', 'str2']]
>>>

Accessing,indexing,slicing items

  Step 3:Let's think about how we can access items from a given list. Lets write another program and name it as list2.py as shown below. We are accessing elements by using integers. Note that the first element accessing starts from index 0 not from index 1. So if total items in a list is five index to access first item is zero and index to access the last item is 4. In our program list2.py we are accessing the first item of list Ls using index 0 and last item by using index 2. In python list we can also access items using negative indexing so for accessing the last item in list Ls we need index -3 and for accessing 2nd item in list Ls we need index -2 and so on. Next we will experiment accessing items from a nested list. List Lss in our program has nested list and the first item from second list inside Lss can be accessed by using Lss[1][0]. Similarly a 3X3 matrix is defined in python by using list Lm. For example to access the second item in the last list defined inside list Lm we use LM[2][2]. To illustrate the slicing feature we have used list Lv which is sliced from original list Ls. the 1:2 indexing strats from item 1 upto item 2 and excluding item 2. If the slicing starts with a : symbol then it will include all items upto the number after : symbol and excluding the number. So for getting a list to have only first 2items of list Ls we slice using Ls[:2]. However if slicing starts with a number and ends with a : symbol it will extract all items starting with the number till the end of the list. In our program list Ln is sliced from the second item till the end using 1:. One last thing we can use with list is a stride. We declared list num having 11 items. By using 1:9:2 the stride number is 2. The stride value tells the compiler to consider only every alternate item. Number 9 tells compiler up to what index item to consider and excluding the index item. If we use only stride like ::3 as illustrated in list num2 we can extract starting from index 0 and till the end of the list.



#!/usr/bin/python

def main():
    Ls = ['abc','def','ghi']
    print ('Accessing element from list Ls')
    print (Ls[0],Ls[2],Ls[-2],Ls[-3])
    Lss = ['str',['str1','str2']]
    print ('Accessing items from a list with nested sublist')
    print (Lss[0],Lss[1][0])
    Lm = [[10,11,12],[20,21,22],[30,31,32]]
    print ('Accessing items from a 3X3 matrix')
    print (Lm[1],Lm[1][0],Lm[2][2])
    Lv = (Ls[1:2])
    print ('printing List after slicing')
    print (Lv)
    Lr = (Ls[:2])
    print ('printing List after one more slicing')
    print (Lr)
    Ln = (Ls[1:])
    print ('Printing List Ln')
    print (Ln)
if __name__ == '__main__':
    main()

  Step 4:The output of program list2.py we wrote in last step is shown below.



>>>
Accessing element from list Ls
abc ghi def abc
Accessing items from a list with nested sublist
str str1
Accessing items from a 3X3 matrix
[20, 21, 22] 20 32
printing List after slicing
['def']
printing List after one more slicing
['abc', 'def']
Printing List Ln
['def', 'ghi']
>>>

Size of list, grow or sink

  Step 5:Lists have no fixed size where as size of the string is fixed. To illustrate this feature lets write another program name it as list3.py as shown below. List Ls has 3items and hence its length is 3 as obtained using len in-built function. Also we can get the content of ist item from list using min function and last item using the max function. You can see in the beginning of the program we declared two lists Ls and Lt where Ls is having 3 string items and Lt having 3 number items. We can concatenate lists like we did in our program for two lists Ls and Lt and finally made a list Lf using + operator. Similarly we can use the repetition feature of list using the * operator. We used * operator for repetition of items of list Ls 4times.



#!/usr/bin/python

def main():
    Ls = ['abc','def','ghi']
    print ('Checking length of list Ls')
    print (len(Ls),min(Ls),max(Ls))
    Lt = [1,2,3]
    print ('Checking length of list Lt')
    Lf = Ls + Lt
    print (Lf)
    print ('Checking length of list Lf')
    print (len(Lf))
    Lm = Ls * 4
    print (Lm)
    print ('Checking length of list Lm')
    print (len(Lm))
if __name__ == '__main__':
    main()


  Step 6: The output of the program list3.py we wrote in last step is shown below. Things to observe is that we could concatenate and repeat the items of list and increase the list size at the end.



>>>
Checking length of list Ls
3 abc ghi
Checking length of list Lt
['abc', 'def', 'ghi', 1, 2, 3]
Checking length of list Lf
6
['abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi']
Checking length of list Lm
12
>>>
Checking length of list Ls
3 abc ghi
Checking length of list Lt
['abc', 'def', 'ghi', 1, 2, 3]
Checking length of list Lf
6
['abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi', 'abc', 'def', 'ghi']
Checking length of list Lm
12
>>>

Updating, deleting values in lists

  Step 1: Lists can be updated and items can also be deleted from the list. Let's write another program list4.py as shown below. We deleted the first item of list Ls using del in-built function. So the modified list has only two items. We can append another item in the existing list Ls using .append function and the item will be added at the end of the list. We can add a new item in the list at any index using the .insert function which takes two arguments, the first argument as the number indicating where to add in the existing list and the second the item content. In our program after we added 'mno' in the position having index 1. If we want to remove the last item from list we can use pop function as shown in the program. If we want to reverse the list items without changing the list item contents we can use the reverse function as illustrated in our program.


#!/usr/bin/python

def main():
    Ls = ['abc','def','ghi']
    del[Ls[0]]
    print ('Checking modified list Ls')
    print (Ls)
    Ls.append('jkl')
    print ('Checking modified list after append is Ls')
    print (Ls)
    Ls.insert(1,'mno')
    print ('Checking modified list after insert is Ls')
    print (Ls)
    Ls.pop()
    print ('Checking modified list after pop is Ls')
    print (Ls)
    Ls.reverse()
    print ('Checking modified list after reverse is Ls')
    print (Ls)


if __name__ == '__main__':
    main()

  Step 2: The output of the program list4.py we wrote in last step is shown below.


>>>
Checking modified list Ls
['def', 'ghi']
Checking modified list after append is Ls
['def', 'ghi', 'jkl']
Checking modified list after insert is Ls
['def', 'mno', 'ghi', 'jkl']
Checking modified list after pop is Ls
['def', 'mno', 'ghi']
Checking modified list after reverse is Ls
['ghi', 'mno', 'def']
>>>

Lists are mutable unlike strings

  Step 3: Next we look at the feature lists are mutable unlike strings. To illustrate this feature lets write another program and name it as list5.py as shown below. We defined a list having 3 string items and we modified strings using the index.


#!/usr/bin/python

def main():
    Lk = ['abc','def','ghi']
    Lk[0] = 'ABC'
    Lk[-2] = 'DEF'
    print ('Checking modified list Lk')
    print (Lk)


if __name__ == '__main__':
    main()

  Step 4: The output of the program list5.py we wrote in last step is shown below.


>>>
Checking modified list Lk
['ABC', 'DEF', 'ghi']
>>>

Exercises, Solutions

High
Medium

Want to contribute a new article? Write and upload your article information .
Share

 Articles

 C Programming

 Linux Software

 Test your skills:online tests

 C Programming

 Python Programming

 Linux Software

 Quantitative Aptitude

 Embedded System Software

 Search code examples

, , , , , , , , , , , , , , , , , ,

 Search MCQs with answers

, , , , , , , , , , , , , , , , ,