Ads Top

Working with Python Lists | Introduction to List Manipulation


The python list are containers that are used to store a list of values of any type. Unlike other variables Python lists are mutable i.e., you can change the elements of a list in place; Python will not create a fresh list when you make changes to an element of a list.


Creating and accessing lists

  [] 				# empty list 
  [1,2,3]			# list of integers 
  ['one','two','three']		#list of strings 

The empty list

The empty list is [].You can also create an empty list as:

L = list()


Nested lists

A list can have an element in it, which itself is a list. Such a list is called nested list, e.g.,

L1 = [3,4,[5,6],7]


Creating lists from existing Sequences

By using built-in list type object you can create lists from sequences where sequence can be any kind of sequence objects including strings, tuples, and lists.

>>> l1 = list('hello')
>>> l1
['h','e','l','l','o']


Most commonly used method to input lists is eval(input()).

list = eval(input("Enter list: "))
print("list you entered: ",list)
eval() tries to identify type by looking at the given expression.

The eval() function


The eval() function of python can be used to evaluate and return the result of an expression given as string.
For example:
eval('5+8')
will give you result as 13

Accessing lists

Similarity with Strings
1. Length
2. Indexing and slicing
3. Membership operators
4. Concatenation and Replication operators

Differences from Strings
Lists are mutable while strings are immutable.

Comparing lists

Comparison Result
[1,2,8,9]<[9,1] True
[1,2,8,9]<[1,2,9,1] True
[1,2,8,9]<[1,2,9,10] True
[1,2,8,9]<[1,2,8,4] False


List Operations

Joining lists

>>> lst1 = [1,3,5]
>>> lst2 = [6,7,8]
>>> lst1 + lst2 [1,3,5,6,7,8]

Replicating lists

>>> lst1 =[1,3,5]
>>> lst1*3
[1,3,5,1,3,5,1,3,5]

Slicing lists

List slices, like string slices are the sub part of a list extracted out. You can use indexes of list elements to create list slices as per followinf format:

seq = L[start:stop]

It creates a list with elements falling between indexes start and stop, not including stop
>>> lst1 = [1,2,5,14,18,20]
>>> lst1[1:4]
[2,5,14]

List also supports slice steps. The slice steps are used as per following format:

seq =L[start:stop:step]

It creates a list with elements falling between indexes start and stop, not including stop, skipping step elements in between.
For example
>>> lst1 = [10,12,14,20,22,24,30,32,34]
>>> lst1[0:10:2]
[10,14,22,30,34]

Include every 2nd element i.e., skip 1 element in between.
>>> lst1 = [10,12,14,20,22,24,30,32,34]
>>> lst1[::3]
[10,20,30]

No start and stop given. Only step is given as 3. That is, from the entire list, pick every 3rd element for the list slice.

Note: List can be reversed like strings by this method.

>>> lst = [1,2,3,4,5]
>>> lst[::-1]
[5,4,3,2,1]

Using Slices for list Modification

The values being assigned must be a sequence.

>>> l = [1,2,3,4,5]
>>> l[2:]="604"
>>> l
[1,2,6,0,4]

See String Slices also.

Updating Elements to a list

To update or change an element of the list in place, you just have to assign new value to the element's index in list as per syntax:

L[index] = <new value>

>>> lst = [1,2,3,4,5]
>>> lst[2]= 6
>>> lst
[1,2,6,4,5]

List functions and methods

1. The index method

This function return the index of first matched item from the list.
List.index(<item>)
>>> lst1 = [11,12,13,11,14,15]
>>> lst1.index(11)
0

It returns the index of first value 11 even if there is another value 11 at index at 3.

2. The append method

This method adds an item to the end of the list.
List.append(<item>)
>>> colors = ['red','yellow','green']
>>> colors.append('blue')
>>> colors
['red','yellow','green','blue']

Note: The append() doest not return the new list, just modifies the original.
It takes exactly one element and returns no value

3. The extend method

This method is also used for adding multiple elements given in the form of list to the list.
List.extend(<list>)
>>> l1 = ['a','b','c']
>>> l2 = ['d','e']
>>> l1.extend(l2)
>>> l1
['a','b','c','d','e']
>>> l2
['d','e']

The elements of l2 are added at the end of the l1 and gives the output ['a','b','c','d','e']
But l2 remains unchanged and gives output ['d','e']

This method takes exactly one element (a list type) and returns no value.

Difference between append() and extend()
The append() function adds one element to a list, while the extend() can add multiple elements from a list supplied to it as argument.
The append() updates the original list but extend() returns the new list.

4. The insert method

This method insert the element at the passed position to the list.
List.insert(<pos>, <item>)

The first argument <pos>is the index of the element before which the second argument item is to be added.

>>> l1 = ['a','e','u']
>>> l1.insert(2,'i')
>>> l1
['a','e','i','u']

list.insert(0,x) will insert element x at the front of the list
list.insert(len(a),x) will insert element x at the end of the
list-index equal to the length of the list;
thus it is equivalent to list.append(x)

5. The pop method

The pop() method is used to remove the item from given position in the list, and return it.
List.pop(<index>)

>>> colors = ['red','yellow','green']
>>> lst = colors.pop(0)
>>> lst
'red'
>>> colors
['yellow','green']

Note: It takes one optional argument and returns a value - the item being deleted.
If no index is specified, pop() removes and returns the last item in the list.

6. The remove method

The remove() method removes the first occurence of given item from the list.
List.remove(<value>)

>>> lst1 = [11,12,13,11,14,15]
>>> lst1.remove(11)
>>> lst1
[12,13,11,14,15]

Note: It takes one essential argument and does not return any thing.
The remove() will report an error if there is no such item in the list.
The pop() method removes an individual item and return it, while removes searches for an item, and removes the first matching item from the list.

7. The clear method

This method removes all the items from the list and the list becomes empty list.
List.clear()

>>> lst1 = [11,12,13,11,14,15]
>>> lst1.clear()
>>> lst1
[]

Note: The clear() function returns nothing
Unlike del<lstname> statement, clear() removes only the elements and not the list elements. After clear(), the list objects still exists as an empty list.

8. The count method

This method returns the count of the item that you passed as argumet and if the given item is not in the list,it return zero.
List.count(<item>)

>>> lst1 = [11,12,13,11,14,15]
>>> lst1.count(11)
2

9. The reverse method

The reverse() reverses the item of the list.
List.reverse()

>>> lst1 = [11,12,13,14,15]
>>> lst1.reverse()
>>> lst1
[15,14,13,12,11]

Note: This method does not create a new list.
It takes no argument, returns no list; reverses the list 'in place' and does not return any thing.

7. The sort method

The sort() method sort the items of the list, by default in increasing order.
List.sort()

>>> lst1 = [11,10,13,9,14,15]
>>> lst1.sort()
>>> lst1
[9,10,11,13,14,15]

Note: It does not create a new list.
To short a list in decreasing order then list.sort(reverse=True)
sort() won't be able to sort the values of a list if it contains a complex number as an element.

second largest element

No comments:

Powered by Blogger.