Example HTML page

Lists in Python

Lists

Another data type in Python is ‘List’. A list is a collection of items separated by commas and enclosed within square brackets [ ]. The values stored in a list can be accessed using the slice operator ([ ] and [:]) with index position starting at 0 from the beginning of the list and in case of reverse accessing of list then the index position is -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Creating lists

We can create a list by inserting some items into a square braces, separated by commas.

Ex

>>> list=[ ]                            #Creating an empty list

>>> list

[ ]

>>> list=[“Hi”,5,1.3]             #Appending elements into list

>>> list

[‘Hi’, 5, 1.3]

Accessing elements in list

We can access the elements in a list by the following way.

>>> x=[“bcd”,8,2003,43.2]

>>> y=[“1″,2,”three”]

>>> x

[‘bcd’, 8, 2003, 43.2]

>>> y

[‘1’, 2, ‘three’]

>>> x[2]

2003

>>> x[1:3]

[8, 2003]

>>> y[0]

‘1’

>>> y[0:1]

[‘1’]

Updating lists

We can update the existing list elements by mentioning the index position of that element and we can replace that element by reassigning a new element to that list. It is shown in below example.

>>> L=[“C++”,”Java”,”Python”]

>>> L

[‘C++’, ‘Java’, ‘Python’]

>>> L[0]=[“C Programming”]                    #Updating C++ with C Programming

>>> L

[[‘C Programming’], ‘Java’, ‘Python’]

>>> L[2]=[“R Programming”]                  #Updating Python with R Programming

>>> L

[[‘C Programming’], ‘Java’, [‘R Programming’]]

Deleting List elements

If you want to delete an element in a list we have to use del statement. It is shown in below:

>>> a=[“a”,”e”,”i”,”o”,”u”]

>>> del a[3]

>>> a

[‘a’, ‘e’, ‘i’, ‘u’]

>>> del a[0:1]

>>> a

[‘e’, ‘i’, ‘u’]

 

>>> m=[[ ]]*4

>>> m

[[ ], [ ], [ ], [ ]]

>>> m[2].append(4)

>>> m

[[4], [4], [4], [4]]

>>> del m[1]

>>> m

[[4], [4], [4]]

Basic List operations

Some of the basic operations on list are shown in below:

>>> a=[“apple”,13,86]                                             #Length of a list

>>> len(a)

3

>>> [1,2,3]+[“a”,”b”,”c”]                                         #Concatenation of two lists

[1, 2, 3, ‘a’, ‘b’, ‘c’]

>>> [“Hey!”,”VMS”]*3                                           #Repetition of elements in a list

[‘Hey!’, ‘VMS’, ‘Hey!’, ‘VMS’, ‘Hey!’, ‘VMS’]

>>> for x in[1,2,3,4,5]:                                            #Iteration

print(x,end=” “)

 

1 2 3 4 5

>>> list=[“12″,”India”,3,40,12.6]                            #Indexing

>>> list

[’12’, ‘India’, 3, 40, 12.6]

>>> list[-2]

40

>>> list[0]

’12’

>>> list[3]

40

>>> list=[“12″,”India”,3,40,12.6]                           #Slicing

>>> list[1:-2]

[‘India’, 3]

>>> list[:1]

[’12’]

>>> list[-1:]

[12.6]

Built-in functions

Python includes the following built-in list functions.

1.List len( )

It returns the number of elements in the list.

Ex

>>> x=[“India”,”China”,”Nepal”,”Japan”,”London”]

>>> x

[‘India’, ‘China’, ‘Nepal’, ‘Japan’, ‘London’]

>>> len(x)

5

2.List max( ) and min( )

This returns the elements with maximum and minimum value from the list.

Ex

>>> x=[“India”,”China”,”Nepal”,”Japan”,”London”]

>>> max(x)

‘Nepal’

>>> y=[256,265,345,435,12.5]

>>> max(y)

435

>>> min(x)

‘China’

>>> min(y)

12.5

>>>

3.list( )

The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list.

Note: Tuple are very similar to lists. The only difference is that element values of a tuple cannot be changed and tuple elements are put in between parentheses instead of square bracket. This function also converts characters in a string into a list.

Ex:

>>> tuple=(123,”C++”,”Java”,”Python”)

>>> tuple

(123, ‘C++’, ‘Java’, ‘Python’)

>>> list(tuple)

[123, ‘C++’, ‘Java’, ‘Python’]

>>> str=”Hello World”

>>> str

‘Hello World’

>>> list1=list(str)

>>> list1

[‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’]

>>>

List methods

The following are the methods of list.

1.append( )

The append( ) method appends an element into the existing list.

Ex

>>> a=[“Python”,3,15.6,2018]

>>> a

[‘Python’, 3, 15.6, 2018]

>>> a.append(‘Programming’)

>>> a

[‘Python’, 3, 15.6, 2018, ‘Programming’]

2.count( )

This method returns the count of how many times an element occurs in the list.

Ex

>>> list=[1,2,3,4,1,2,3,5,2]

>>> list.count(2)

3

>>> list.count(5)

1

>>> list.count(7)

0

3.extend( )

This method appends the contents of one list to another list.

Ex

>>> m=[‘a’,’b’,’c’,’d’]

>>> n=[‘e’,’f’,’g’,’h’]

>>> m.extend(n)

>>> m

[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]

4.index( )

This method returns the index position of an element in list.

Ex

>>> List

[‘A’, ‘Step’, ‘To’, ‘Learn’]

>>> List.index(‘To’)

2

>>> List.index(‘Step’)

1

5.insert( ) and remove( )

This method inserts and removes an element into an existing list.

Ex

>>> k=[‘A’,’B’,’D’,’F’,’G’]

>>> k

[‘A’, ‘B’, ‘D’, ‘F’, ‘G’]

>>> k.insert(2,”C”)                              #Inserting an element

>>> k

[‘A’, ‘B’, ‘C’, ‘D’, ‘F’, ‘G’]

>>> k.insert(4,”E”)

>>> k

[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’]

>>> k.remove(‘D’)                                #Removing an element

>>> k

[‘A’, ‘B’, ‘F’, ‘G’]

>>> k.remove(“F”)

6.reverse( )

This reverses the position of elements in a list.

Ex

>>> b=[‘1′,’2′,’3′,’4′,’5’]

>>> b

[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

>>> b.reverse( )

>>> b

[‘5’, ‘4’, ‘3’, ‘2’, ‘1’]

7.sort( )

This method sorts the elements of list.

Ex

>>> d=[“C”,”Java”,”.net”,”Python”]

>>> d

[‘C’, ‘Java’, ‘.net’, ‘Python’]

>>> d.sort( )

>>> d

[‘.net’, ‘C’, ‘Java’, ‘Python’]

Example programs on lists

1.A python program on lists to print the squares of numbers.

def squares( ):
	x = list( )
	for y in range(1,21):
		x.append(y**2)
	print(x)		
squares( )

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

2.A python program on lists to store the list of different items in list and to display whether the list if full or not.

items=["bread","milkpacket","sugar","bun","jam"]
if (len(items)<4):
    print(items)
    print(items.sort())
else:
    print("list is full")

Output

list is full
Example HTML page

Leave a Reply

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

Pin It on Pinterest