2. Lists
Like a String, List also is, sequence data
type.
In a string we have only characters but a
list consists of data of multiple data types
It is an ordered set of values enclosed in
square brackets [].
We can use index in square brackets []
Values in the list are called elements or
items.
A list can be modified, i.e. it is mutable.
3. List index works the same way as
String index :
An integer value/expression can be
used as index
An Index Error appears, if you try and
access element that does not exist in
the list
IndexError: list index out of range
An index can have a negative value, in
that case counting happens from the
end of the list.
4. List Examples
i) L1 = [1,2,3,4] list of 4 integer elements.
ii) L2 = [“Delhi”, “Chennai”, “Mumbai”]
list of 3 string
elements.
iii) L3 = [ ] empty list i.e. list with no element
iv) L4 = [“abc”, 10, 20]
list with different types of
elements
5. Example of list:
list = [ ‘XYZ', 456 , 2.23, ‘PNB', 70.2 ]
tinylist = [123, ‘HMV']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements 2nd & 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
6. Traversing a List
Using while loop
L=[1,2,3,4]
i = 0
while i < 4:
print (L[i])
i + = 1
Output
1 2 3 4
7. Traversing a List
Using for loop
L=[1,2,3,4,5]
L1=[1,2,3,4,5]
for i in L: for i in range (5):
print(i) print(L1[i])
Output: Output:
1 2 3 4 5 1 2 3 4 5
8. List Slices
Examples
>>> L=[10,20,30,40,50]
>>> print(L[1:4])
[20, 30, 40] #print elements 1st index to 3rd index
>>> print(L[3:])
[40, 50] #print elements from 3rd index onwards
>>> print(L[:3])
[10, 20, 30] #print elements 0th index to 2nd index
>>> print L[0:5:2]
[10, 30, 50] #print elements 0th to 4th index jump 2 steps
9. append() method
to add one element at the end
Example:
>>> l=[1,2,3,4]
>>> print(l)
[1, 2, 3, 4]
>>> l.append(5)
>>> print(l)
[1, 2, 3, 4, 5]
10. extend() method
To add more than one element at the
end of the list
Example
>>> l1=[10,20,30]
>>> l2=[100,200,300]
>>> l1.extend(l2)
>>> print(l1)
[10, 20, 30, 100, 200, 300]
>>> print(l2)
[100, 200, 300]
11. pop , del and remove functions
For removing element from the list
if index is known, we can use pop() or
del() method
if the index is not known,
remove ( ) can be used.
to remove more than one element, del
( ) with list slice can be used.
18. Tuples
We saw earlier that a list is
an ordered mutable collection.There’s
also an ordered immutable collection.
In Python these are called tuples and
look very similar to lists, but typically
written with () instead of []:
a_list = [1, 'two', 3.0]
a_tuple = (1, 'two', 3.0)
19. Similar to how we used list before, you
can also create a tuple.
The difference being that tuples are
immutable.This means no assignment,
append, insert, pop, etc. Everything else
works as it did with lists: indexing, getting
the length etc.
Like lists, all of the common sequence
operations are available.
20. Example of Tuple:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple ) # Prints complete list
print (tuple[0]) # Prints first element of the list
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints list two times
print 9tuple + tinytuple) # Prints concatenated lists
21. The following code is invalid with tuple, because
we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 #Valid syntax with list
22. Lists
• A sequence of values of any type
•Values in the list are called items
and are indexed
•Are mutable
•Are enclosed in []
Example
[‘spam’ , 20, 13.5]
Tuple
• are sequence of values of any type
•Are indexed by integers
•Are immutable
•Are enclosed in ()
Example
(2,4)
23. Dictionary
Python's dictionaries are kind of hash table type.
They work like associative arrays and consist of
key-value pairs.
Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using
square braces ([])
24. Commonly used dict methods:
keys() - returns an iterable of all keys in
the dictionary.
values() - returns an iterable of all
values in the dictionary.
items() - returns an iterable list of (key,
value) tuples.
25. Example of Dictionary
dict = {'name': ‘Ram','code':1234, 'dept': ‘KVS'}
print(dict) # Prints complete dictionary
print(dict.keys()) # Prints all the keys
print(dict.values()) # Prints all the values
print(dict.items())
Output:
{'dept': 'KVS', 'code': 1234, 'name': 'Ram'}
['dept', 'code', 'name']
['KVS', 1234, 'Ram']
[('dept', 'KVS'), ('code', 1234), ('name', 'Ram')]
26. there is a second way to
declare a dict:
sound = dict(dog='bark', cat='meow', snake='hiss')
print(sound.keys()) # Prints all the keys
print(sound.values()) # Prints all the values
Output:
['cat', 'dog', 'snake']
['meow', 'bark', 'hiss']
27. A few things we already saw on
list work the same for dict:
Similarly to how we can index into lists we use
d[key] to access specific elements in the dict.There
are also a number of methods available for
manipulating & using data from dict.
len(d) gets the number of item in the dictionary.
print (len(dict))
key in d checks if k is a key in the dictionary. print
('name' in dict) (True/False)
d.pop(key) pops an item out of the dictionary
and returns it, similarly to how list’s pop method
worked. dict.pop('name')