Python- The Lists

LIST

List is a built-in data type where the literals are enclosed within the square brackets []

To declare a list, put the list of literals in a square bracket:

fruits = [‘Mango’,’Apple’,’Orange’]

 

We can access the list using indexes, starting from 0 or using a for loop.

The IN operator lets us check if an element appears in the list.

The output once you run the above program:

 

Some of the common methods to manipulate the list are:

list.append(element) : Adds a single element to the end of the list.

list.reverse : Reverses the list.

list.sort : Sorts the list

list.remove(element) : Removes the first instance of the element

list.insert(index,element) : Inserts the element at the given index

list.extend(list2) : Adds all the elements of list2 at the end of list. Similar to list+list2

list.pop(index) : Removes and returns the element at the given index

list.index(element) : Returns the index of the given element, starting from first.

We can test for all of the above methods using the simple program:

fruits = [‘Mango’,’Apple’,’Orange’]
veg =[‘Potato’,’Cabbage’]

print (fruits)

fruits.append(‘Banana’)
fruits.reverse()
print (‘After reverse and append :’,fruits)

fruits.sort()
print (‘After Sort :’,fruits)

fruits.remove(‘Mango’)
print (‘After Remove :’,fruits)

fruits.insert(0,’Grapes’)
print (‘After Insert :’,fruits)

fruits.extend(veg)
print (‘After Extend :’,fruits)

fruits.pop(4)
print (‘After Pop :’,fruits)

print(‘Orange is at position : ‘,fruits.index(‘Orange’))

The output of the above program:

 

[‘Mango’, ‘Apple’, ‘Orange’]
After reverse and append : [‘Banana’, ‘Orange’, ‘Apple’, ‘Mango’]
After Sort : [‘Apple’, ‘Banana’, ‘Mango’, ‘Orange’]
After Remove : [‘Apple’, ‘Banana’, ‘Orange’]
After Insert : [‘Grapes’, ‘Apple’, ‘Banana’, ‘Orange’]
After Extend : [‘Grapes’, ‘Apple’, ‘Banana’, ‘Orange’, ‘Potato’, ‘Cabbage’]
After Pop : [‘Grapes’, ‘Apple’, ‘Banana’, ‘Orange’, ‘Cabbage’]
Orange is at position : 3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s