The list type is a container, that implements the sequence protocol. List holds the number of objects in a given order and it allows add and remove objects from the sequence. List literals are written with in square brackets [].
To creare a list, put a number of expressions in square brackets.
Syntax:
L = [ ]
L = [expression, .....]
Example:>>> colors=['red','green','blue','red']
>>> colors
['red', 'green', 'blue', 'red']
>>>
>>> numbers=[45,67,23,87]
>>> numbers
[45, 67, 23, 87]
This construct is known as a “list display”. Python also supports computed lists, called “list comprehensions”. I will discuss about it in later posts.
We can also use the built-in list type object to create list.
L = list() #empty list
Example:
>>> numbers=[45,67,23,87]
>>> numbers
[45, 67, 23, 87]
>>>
>>> num=list(numbers)
>>> num
[45, 67, 23, 87]
>>>
Index values are used to access the elements from the list.>>> num[1]
67
>>> num[3]
87
Python never creates a new list if you assign a list to a variable. Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.A = []
b = A # Both will point to the same list.
Example:
>>> a=['alice','bob']
>>> b=a # list 'a' aasign to 'b'
>>> b
['alice', 'bob']
>>> a.remove('alice') # Remove an item from list 'a'
>>> b # Item is also removes from list 'b'
['bob']
This shows that the two variables 'a' and 'b' pointing to the same memory location.
The '+' works to append two lists,
>>> [1,2]+[5,6]
[1, 2, 5, 6]
The for construct 'for var in list ' is an easy way to look at each element in a list.
>>> names = ['alice','bob']
>>> for name in names :
... print name
...
alice
bob
If you need both the index and the item, use the enumerate function:
>>> for index,name in enumerate(names):
... print index, name
...
0 alice
1 bob
If you need only the index, use range and len:
>>> for index in range(len(names)):
... print index
...
0
1
The list object supports the iterator protocol. To explicitly create an iterator, use the built-in iter function:
>>> i=iter(names)
>>> item=i.next()
>>> item
'alice'
>>> item=i.next()
>>> item
'bob'
If a list contains numbers, the built-in sum function gives you the sum:
>>> num=[34,56,23,80]
>>> total=sum(num)
>>> total
193
>>> colors
['red', 'green', 'blue', 'red']
>>> names=''.join(colors) >>> names 'redgreenbluered' Modifying Lists Index values are used to assign values to list. >>> names[1]='tom' # assign new value to list 'names' >>> names ['alice', 'tom']
If multiple variables that point to the same list, all variables will be updated at the same time.
>>> names=['alice','bob']
>>> name=names
>>> names.append('tom')
>>> name
['alice', 'bob', 'tom']
>>> names
['alice', 'bob', 'tom']
Here both name and names are updated at the same time.
To create a separate list, you can use slicing or the list function to quickly create a copy:
>>> name=names[:]
>>> name
['alice', 'bob', 'tom']
>>> names.append('Rose')
>>> names
['alice', 'bob', 'tom', 'Rose']
>>> name
['alice', 'bob', 'tom']
Other list functions are:
- list.append(elem) -- adds a single element to the end of the list.
- list.insert(index, elem) -- inserts the element at the given index
- list.extend(list2) adds the elements in list2 to the end of the list.
- list.index(elem) -- searches for the given element from the start of the list and returns its index.
- list.remove(elem) -- searches for the first instance of the given element and removes it.
- list.sort() -- sorts the list in place (does not return it).
- list.reverse() -- reverses the list in place (does not return it)
- list.pop(index) -- removes and returns the element at the given index.
Searching List
The in operator can be used to check if an item is present in the list:
>>> if 'alice' in names:
... print 'Name exist'
...
Name exist
To get the index of the first matching item, use index:
>>> i=names.index('tom')
>>> print i
2
The index method does a linear search, and stops at the first matching item. If no matching item is found, it raises a ValueError exception.
No comments:
Post a Comment