Lists

Lists is a compound data types, used to group together other values written as a list of comma-separated values (items) between square brackets . Lists might contain items of different types, but usually the items all have the same type.

>>> squares = [1, 4, 9, 16, 25] 
>>> squares [1, 4, 9, 16, 25]

Lists can be indexed and sliced:
 
>>> squares[0] # indexing returns the item 
1  
>>> squares[-1] 
25 
>>> squares[-3:] # slicing returns a new list 
[9, 16, 25]
 
 
Note : Index 0 for the first item and -1 for the last item .

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:
>>>
>>> squares[:] 
[1, 4, 9, 16, 25]


Lists also support operations like concatenation:
>>>
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:
>>>
>>> cubes = [1, 8, 27, 65, 125] # something's wrong here  
>>> 4 ** 3 # the cube of 4 is 64, not 65!  
64  
>>> cubes[3] = 64 # replace the wrong value  
>>> cubes 
[1, 8, 27, 64, 125]


Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

You can also add new items at the end of the list, by using the append() method 
>>> cubes.append(216) # add the cube of 6 
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes 
 [1, 8, 27, 64, 125, 216, 343]

 
The built-in function len() also applies to lists:
>>>
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
 
It is possible to nest lists (create lists containing other lists), for example:
>>>
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
 

More on Lists

The list data type has some more methods. Here are all of the methods of list objects:

1. list.append(x) :
Add an item to the end of the list. Equivalent to a[len(a):] = [x].

2.list.extend(L) :
Extend the list by appending all the items in the given list L. 
Equivalent to a[len(a):] = L.
squares = [1, 4, 9, 16, 25]
cubes=[1,8,27,64,125]
squares.extend(cubes)
squares
[1, 4, 9, 16, 25, 1, 8, 27, 64, 125]

Note : Concatenation of lists
Equivalent to : squares=squares+cubes
3. list.insert(i,x):
Insert an item x at a given position . The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) i.e insert the element at the end of the list .
4.list.remove(x):
Remove the first item from the list whose value is x. It is an error if there is no such item.
5.list.pop([i]) :
Remove the item at the given position i in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position
same as del
 6.list.clear():
Remove all items from the list. Equivalent to del a[:].
Returns an empty list
Note : Supported in Python 3
7. list.index(x):
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
8.list.count(x):
Return the number of times x appears in the list.
9.list.sort([reverse=True/False])
Sort the items of the list in ascending order by default i.e reverse=False
Returns the sorted list .
sorted(list) : Return a new sorted list from the items in iterable
10.list.reverse()  :
Reverse the elements of the list in place.
11.list.copy() :
Return a shallow copy of the list. Equivalent to a[:].

 Note :ou might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None

Using Lists as Stacks (LIFO)

append() : Last In (add an element at the end of the list)
pop (): First Out (Remove the last element of list  without an explicit index) 

Using Lists as Queues(FIFO):

While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])



List Comprehensions:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:

squares = [x**2 for x in range(10)]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(x, x**2) for x in range(6)]
[str(round(pi, i)) for i in range(1, 6)]
 ['3.1', '3.14', '3.142', '3.1416', '3.14159']

Nested List Comprehensions

The zip() function would do a great job for this use case:
squares = [1, 4,9, 3,16, 25]
cubes=[1,8,27,64,125]
test=['a','b','c','d','e']

 zip(squares,cubes)
 [(1, 1), (4, 8), (9, 27), (3, 64), (16, 125)]
zip(squares,cubes,test)
 [(1, 1, 'a'), (4, 8, 'b'), (9, 27, 'c'), (3, 64, 'd'), (16, 125, 'e')]

Note : Return the List of Tuples

 

 The del statement

There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
del can also be used to delete entire variables:
>>>
>>> del a
Referencing the name a hereafter is an error (at least until another value is assigned to it)

Note : Same as pop()

Important Notes :

Q1.Difference between del and remove() and pop() ?
del : remove the elements at the specified index
remove : remove the first specified value in the list
pop : remove the last element if no index is specified wheras in  del it gives syntax error if no index is defined .

Q2. Difference between sort and sorted?
sort : gives the same list with sorted elements
sorted : gives the shallow copy (new list ) with sorted elements

Note : List is passed in function by call by Reference i.e it will affect the original list .
 

0 comments:

Copyright © 2013 SoftKul