2. LIST DEFINITION
• A list is an ordered set of values, where each
value is identified by an index.
• The values that make up a list are called its
elements.
• Lists and strings and other things that behave
like ordered sets are called sequences.
• Updating in the existing list is possible.
4. ACCESSING ELEMENTS IN LIST
>>>LIST2=[1,2,3,4,5]
>>> print(LIST2[0])
1
>>>print(LIST2[-1])
5
>>>WORDS=[“hello”, “hai”]
>>>print (WORDS[1])
hai
5. UPDATING IN A LIST
• In list you can add the element using the
method append()
• list.append(obj)
Example
>>> list2=[1,2,3,4,5]
>>>list2.append(9)
>>>print (list2[])
[1,2,3,4,5,9]
6. Delete list elements
• To remove a element in a list, you can use either del statement
if you exactly know which elements you are deleting or
remove() method if you don’t know.
• Example
>>>numbers=[17, 123,54,78,99,45,67]
>>>del list[2]
>>>print(numbers[])
[17, 123,78,99,45,67]
>>>numbers.remove(123)
>>>print(numbers[])
[17,78,99,45,67]
7. List operations
• 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.
8. BASIC LIST OPERATIONS
PYTHON EXXPRESSION RESULTS DESCRIPTION
Len([1,2,3]) 3 length
[1,2,3]+[4,5] [1,2,3,4,5] concatenation
[‘hi’]*2 [‘hi’ ‘hi’] repetition
2 in [1,2,3],
5 not in [1,2,4]
True
True Membership
for x in [1,2,3,4,5] 1 2 3 4 5 iteration
9. List slices
• A subsequence of a sequence is called a slice
and the operation that extracts a subsequence
is called slicing.
• Like with indexing, we use square brackets ([ ])
as the slice operator, but instead of one
integer value inside we have two, separated
by a colon (:)
12. List .append()
• append(x) method is used to add an item to
the end of a list.
• Example
>>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>>Veggies.append(potato)
>>>Print(veggies[])
[‘carrot’,’cabbage’,’beetroot’,’beans’,’potato’]
13. List.insert()
• The list.insert(i,x) method takes two arguments,
with i being the index position you would like to
add an item to, and x being the item itself.
• Example
>>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>>veggies.insert(3,’brinjal’)
>>>print(veggies[])
[‘carrot’,’cabbage’,’beetroot’,’brinjal’,’beans’]
14. List.extend()
• The list.extend(L) method, which takes in a
second list as its argument.
• Example
• >>>fruits=[‘apple’,’orange’,’grapes’]
• >>>veggies.extend(fruits)
• >>>print(veggies[])
[‘carrot’,’cabbage’,’beetroot’,’beans’,‘apple’,
’orange’,’grapes’]
15. List.remove()
• To remove an item from a list
• remove(x) method which removes the first item
in a list whose value is equivalent to x
• Example
• >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
• >>>veggies.remove(‘cabbage’)
• >>>print(veggies[])
[‘carrot’,’beetroot’,’beans’]
16. List.pop()
• The list.pop([i]) method to return the item
at the given index position from the list
and then remove that item.
>>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>>print(veggies.pop(2))
>>>print(veggies[])
[‘carrot’,’cabbage’,’beans’]
17. list.index()
• lists start to get long, it becomes more difficult
for us to count out our items to determine at
what index position a certain value is located.
• >>>Veggies=[‘carrot’,’cabbage’,’beetroot’,’beans’]
>>> print(veggies.index(‘beans’))
3
18. list.copy()
• If working with a list and may want to
manipulate it in multiple ways while still
having the original list available to us
unchanged, we can use list.copy() to make a
copy of the list.
• >>>items=veggies.copy()
• >>>print(items[])
[‘carrot’,’cabbage’,’beetroot’,’beans’]
19. list.reverse()
• Reverse the order of items in a list by using
the list.reverse() method.
>>>veggies.reverse()
>>>print(veggies[])
[‘beans’,’beetroot’,’cabbage’,’carrot’]
20. list.count()
• The list.count(x) method will return the
number of times the value x occurs within a
specified list.
>>>print(veggies.count())
4
21. List.sort()
• The list.sort() method to sort the items in a
list.
>>>list=[5,6,3,9,1]
>>>list.sort()
>>>print(list[])
[1,3,5,6,9]
22. List.clear()
• To remove all values contained in it by using
the list.clear() method.
>>>veggies.clear()
>>>print(veggies[])
[]
24. List Loop
• A loop is a block of code that repeats itself
until it runs out of items to work with, or until
a certain condition is met.
• Tour=[‘chennai’,’mumbai’,’banglore’,’australia’]
for t in tour
print(t)
30. ALIASING
• if we assign one variable to another, both
variables refer to the same object.
>>>a=[13,14,6,8,9]
>>>b=a
>>>a is b
true
31. CLONING LISTS
• If we want to modify a list and also keep a
copy of the original, we need to be able to
make a copy of the list itself, not just the
reference.
• This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
33. List parameters
• Passing a list as an argument actually passes a
reference to the list, not a copy of the list.
Example: def double (a_list):
34. Tuples
• A tuple is a sequence of immutable Python objects.
• Tuples are sequences, just like lists.
• Examples
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = ("a", "b", "c", "d“)
35. Accessing Values in Tuples
• To access values in tuple, use the square brackets for slicing
along with the index or indices to obtain value available at that
index.
• Example
>>>tup1 = ('physics', 'chemistry', 1997, 2000)
>>> tup2 = (1, 2, 3, 4, 5, 6, 7 )
>>>print ("tup1[0]: ", tup1[0] ) #for positive indexing
>>>print ("tup2[1:5]: ", tup2[1:5]) # for slicing
Output:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
36. Updating Tuples
• Tuples are immutable which means you
cannot update or change the values of tuple
elements.
• But it can be able to take portions of existing
tuples to create new tuples as the following
example demonstrates
37. >>>tup1 = (12, 34.56);
>>>tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
tup1[0] = 100;
# So let's create a new tuple as follows
>>>tup3 = tup1 + tup2;
>>>print (tup3)
Output:
(12, 34.56, 'abc', 'xyz')
38. Delete Tuple Elements
• Removing individual tuple elements is not possible.
Example:
tup = ('physics', 'chemistry', 1997, 2000)
print (tup)
del (tup )
print ("After deleting tup : " print tup)
Output:
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last): File "test.py", line 9, in <module>
print (tup);
NameError: name 'tup' is not defined
39. Python Tuple Methods
Python Tuple Method
• count(x) -Return the number of items that is
equal to x
• index(x) -Return index of first item that is
equal to x
41. Built-in Tuple Functions
cmp(tuple1, tuple2)-Compares elements of both tuples.
len(tuple)-Gives the total length of the tuple.
max(tuple)-Returns item from the tuple with max value.
min(tuple)-Returns item from the tuple with min value.
tuple(seq)-Converts a list into tuple
42. Tuple Membership Test
my_tuple = ('a','p','p','l','e',)
# In operation
# Output: True
print('a' in my_tuple)
# Output: False
print('b' in my_tuple)
# Not in operation
# Output: True
print('g' not in my_tuple)
43. Comparing tuples
• The comparison operators work with tuples
and other sequences.
• Python starts by comparing the first element
from each sequence.
44. Decorate
• A sequence by building a list of tuples with
one or more sort keys preceding the elements
from the sequence
49. Definition for dictionaries
• Python dictionary is an unordered collection
of items.
• While other compound data types have only
value as an element, a dictionary has a key:
value pair.
• Dictionaries are enclosed by curly braces ({ })
and values can be assigned and accessed using
square braces ([]).
50. # empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
51. Access elements from a dictionary
my_dict = {'name':'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
52. change or add elements in a dictionary
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name':
'Jack'}
print(my_dict)
53. delete or remove elements from a dictionary
• Either remove individual dictionary elements
or clear the entire contents of a dictionary.
• You can also delete entire dictionary in a single
operation.
• To explicitly remove an entire dictionary, just
use the del statement.
54. dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'];
# remove entry with key 'Name'
dict.clear();
# remove all entries in dict
del dict ;
# delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']