Unit 3 Topic List
Unit 3 Topic List
1.1 List
1.2 Tuples
1.3 Sets
1.4 Dictionaries
1
List in Python:
3.1.1 Defining lists,
accessing values in list,
deleting values in list,
updating lists.
3.1.2 Basic List Operations
3.1.3 Built - in List functions
2
List in Python:
The most basic data structure in Python is the sequence.
Each element of a sequence is assigned a number - its
position or index.
The first index is zero, the second index is one, and so
forth.
Python has six built-in types of sequences(strings, Unicode
strings, lists, tuples, buffers, and xrange objects.) , but the
most common ones are lists and tuples.
There are certain things you can do with all sequence types.
These operations include indexing, slicing, adding,
multiplying, and checking for membership.
In addition, Python has built-in functions for finding the
length of a sequence and for finding its largest and smallest
elements. 3
List in Python: Defining Lists
The list is a most versatile datatype available in Python
which can be written as a list of comma-separated values
(items) between square brackets.
Important thing about a list is that items in a list need not be
of the same type.
Example
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
In Python programming, a list is created by placing
all the items (elements) inside a square bracket [ ],
separated by commas.
4
List in Python: Defining Lists
It can have any number of items and they may be of
different types (integer, float, string etc.).
# empty list
my_list = [ ]
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is
called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
5
List in Python: Accessing values in List
There are various ways in which we can access the elements
of a list.
We can use the index operator [ ] to access an item in a
list.
Index starts from 0. So, a list having 5 elements will have
index from 0 to 4.
Trying to access an element other that this will raise an
IndexError.
The index must be an integer.
We can't use float or other types, this will result into
TypeError.
Nested list are accessed using nested indexing.
A list may also contain tuples or so.
6
List in Python: Accessing values in List
my_list = ['p','r','o','b','e']
print(my_list[0]) # Output: p
print(my_list[2]) # Output: o
print(my_list[4]) # Output: e
# Error! Only integer can be used for indexing
my_list[4.0]
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
print(n_list[0][1]) # Output: a
print(n_list[1][3]) # Output: 5
7
List in Python: Negative indexing
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
8
List in Python: Deleting Values in Lists
We can delete one or more items from a list using the
keyword del.
It can even delete the list entirely.
my_list = ['p','r','o','b','l','e','m']
del my_list[2] # delete one item
print(my_list) # Output: ['p', 'r', 'b', 'l', 'e', 'm']
del my_list[1:5] # delete multiple items
print(my_list) # Output: ['p', 'm']
del my_list # delete entire list
print(my_list) # Error: List not defined
9
List in Python: Deleting Values in Lists
We can use remove() method to remove the given item
or pop() method to remove an item at the given index.
The pop() method removes and returns the last item if
index is not provided.
This helps us implement lists as stacks (first in, last out data
structure).
We can use pop() with negative or null index.
We can also use the clear() method to empty a list.
10
List in Python: Deleting Values in Lists
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list) # Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list.pop(1)) # Output: 'o'
print(my_list) # Output: ['r', 'b', 'l', 'e', 'm']
print(my_list.pop()) # Output: 'm'
print(my_list) # Output: ['r', 'b', 'l', 'e']
my_list.clear()
print(my_list) # Output: []
11
List in Python: Deleting Values in Lists
# programming languages list
languages = ['Python','Java','C++','French','C']
# Updated List
print('Updated List:', languages)
12
List in Python: Deleting Values in Lists
Finally, we can also delete items in a list by assigning
an empty list to a slice of elements.
13
List in Python: Slicing Lists
We can access a range of items in a list by using the slicing
operator : (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
14
List in Python: Updating Lists
List are mutable, meaning, their elements can be
changed unlike string or tuple.
We can use assignment operator (=) to change an item
or a range of items.
odd = [2, 4, 6, 8]
15
List in Python: Updating Lists
We can add one item to a list using append() method
And add several items using extend() method.
Examlple
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)
16
List in Python: Updating Lists
We can also use + operator to combine two lists. This is
also called concatenation.
The * operator repeats a list for the given number of
times.
Example
odd = [1, 3, 5]
17
List in Python: Updating Lists
Furthermore, we can insert one item at a desired location
by using the method insert() or insert multiple items by
squeezing it into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)
odd[2:2] = [5, 7]
18
List in Python: Basic List Operation
Lists respond to the + and * operators much like strings; they
mean concatenation and repetition here too, except that the
result is a new list, not a string.
In fact, lists respond to all of the general sequence operations
we used on strings in the prior chapter.
Python Results Description
Expression
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', Repetition
'Hi!']
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: 123 Iteration
print x,
19
List in Python: Built-in Functions
Sr. Function Description
1 cmp(list1, list2) Compares elements of both lists. (Works only in Python 2.x)
2 len(list) Gives the total length of the list.
3 max(list) Returns item from the list with max value.
4 min(list) Returns item from the list with min value.
5 list(seq) Converts a tuple into list.
6 sum(list) Display sum of all elements in list
It returns a sorted version of the list, but does not change the
7 Sorted(list)
original one.
It returns True if even one item in the Python list has a True
8 any(list)
value.
9 all(list) It returns True if all items in the list have a True value.
20
List in Python: Built-in Methods
Sr. Description
Methods
No.
1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in list
3 list.extend(seq) Appends the contents of seq to list
4 list.index(obj) Returns the lowest index in list that obj appears
5 list.insert(index, obj) Inserts object obj into list at offset index
6 list.pop(obj=list[-1]) Removes and returns last object or obj from list
7 list.remove(obj) Removes object obj from list
8 list.reverse() Reverses objects of list in place
9 list.sort() Sorts objects of list, use compare func if given
10 New=old.copy() Shallow copy the new list
11 List.clear() It empties the Python list.
21