Unit 3-1
Unit 3-1
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership.
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.
List Index
We can use the index operator [ ] to access an item in a list. In Python, indices start at 0. So, a list
having 5 elements will have an index from 0 to 4.
x = ['h', 'e', 'l', 'l', 'o']
# Nested List
x_list = ["Happy", [2, 0, 1, 3]]
print(x_list[0][1]) #a
print(x_list[1][3]) #3
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the
second last item and so on.
x = ['h','e','l','l','o']
List Slicing
We can access a range of items in a list by using the slicing operator.
We can get sublist of the list using syntax:
List(start:stop:step)
Where start –starting index of the list
Stop—last index of the list
x = ['h','e','l','l','0','w','o','r','l','d']
print(x[5:]) # elements from index 5 to end: ['w', 'o', 'r', 'l', 'd']
print(x[:]) # elements beginning to end:['h', 'e', 'l', 'l', '0', 'w', 'o', 'r', 'l', 'd']
x=[10,20,30,40,50,60,70]
print(x[1:6:2]) #Out put: [20, 40, 60]
x = [2, 4, 6, 8]
print(x)
x.append(7)
print(x) Output: [1, 3, 5, 7]
x[2:2] = [5, 7]
print(x.pop(1))
print(x.pop())
x.clear()
print(x) # Output: []
Iterating Through a List
Using a for loop we can iterate through each item in a list.
for fruit in ['apple','banana','mango']:
print(fruit)
Output:
apple
banana
mango
Reverse a List: The reverse () method reverses the elements of the list.
x = ['h', 'e', 'l', 'l', 'o'] Output:
x.reverse() ['o', 'l', 'l', 'e', 'h']
print(x)
Sort List: The sort() method sorts the items of a list in ascending or descending order.
x = ['w', 'o', 'r', 'l', 'd'] x=[10,2,56,3] x=[10,2,56,3]
x.sort() x.sort() x.sort(reverse=True)
print(x) print(x) print(x)
Output: ['d', 'l', 'o', 'r', 'w'] Output: [2, 3, 10, 56] Output: [56, 10, 3, 2]
Characteristics of Tuple:
It is ordered.
It allows duplicate members.
It is immutable type(We cannot modify its element after it is created)
Elements of Tuple can access by index.
To use a tuple, you must declare it first. It is declare using ( ) brackets and separate values with
commas.
A tuple can also be created without using parentheses. This is known as tuple packing
Example:
Example 1: Example 2:
>>> x=(1,2,3) >>> x=()
>>> print(x) >>> x
Output: (1, 2, 3) Output: ()
>>> x
Output: (1, 2, 3)
Example 3: Example 4:
>>> x=[4,5,66,9] >>> x=1,2,3,4
>>> y=tuple(x) >>> x
>>> y Output: (1, 2, 3, 4)
Output: (4, 5, 66, 9)
Example 5: # tuple with mixed Example 6: nested tuple
datatypes >>>x=("hello",[1,2,3],(4,5,6))
>>>x=(1,"hello",3.14) >>>x
>>>print(x) Output: ('hello', [1, 2, 3], (4, 5, 6))
Output: (1, 'hello', 3.14)
A tuple can also be created without using parentheses. This is known as tuple packing.
x = 1,3.14,"hello"
print(x) # (1,3.14,’hello’)
a, b, c = x # tuple unpacking
print(a) #1
print(b) #3.14
print(c) # hello
Operations on Tuples
Access tuple items(indexing, negative indexing and Slicing)
Change tuple items
Loop through a tuple
Count()
Length()
Negative Indexing: Python allows negative indexing for its sequences. The index of -1 refers to the
last item, -2 to the second last item and so on.
Slicing
We can access a range of items in a tuple by using the slicing operator colon :
x=(2,4,6,8) x=(2,4,6,8)
print(x[:]) #Out put: (2, 4, 6, 8) print(x[-1]) #Out put:8
print(x[1:]) # Out put: (4, 6, 8) print(x[-3:]) #Out put: (4, 6, 8)
print(x[:2]) #Out put: (2, 4) print(x[:-2]) #Out put: (2, 4)
print(x[1:3]) #Out put: (4, 6) print(x[-3:-1]) #Out put: (4, 6)
x = ('h','e','l','l','o','w','o','r','l','d')
print(x[1:4])
print(x[:-7])
print(x[7:])
print(x[:])
Output:
('e', 'l', 'l')
('h', 'e', 'l')
('r', 'l', 'd')
('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
Change tuple items: Once a tuple is created, you cannot change its values. Tuples are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Output:
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module> x[1]=10
Example:
x = (4, 2, 3, [6, 5])
x[3][0] = 9
print(x)
Output:
(4, 2, 3, [9, 5])
('h', 'e', 'l', 'l', 'o')
Loop through a tuple(Iteration): We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
Output:
4
5
6
7
2
aa
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
Output: 12
Concatenation: We can use + operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using the * operator.
Both + and * operations result in a new tuple.
Example:
print((1, 2, 3) + (4, 5, 6))
print(("Repeat",) * 3)
Output:
(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')
Deleting a Tuple: we cannot change the elements in a tuple. It means that we cannot delete or remove
items from a tuple.
Example:
x = (1,2,3)
del x
print(x)
Output:
Traceback (most recent call last):
File "<string>", line 8, in <module>
NameError: name 'x' is not defined
Tuple Methods
Output:
2
1
Example:
Example 1: Example 2:
x = {1, 2, 3} # set of mixed datatypes
print(x) x = {1.0, "Hello", (1, 2, 3)}
print(x)
Output:
{1, 2, 3} Output:
{1.0, (1, 2, 3), 'Hello'}
Example 3: Example 4:
# set cannot have duplicates x = set([1, 2, 3, 2])
x = {1, 2, 3, 4, 3, 2} print(x)
print(x)
Output: Output:
{1, 2, 3, 4} {1, 2, 3}
Example 5:
x= set()
print(type(x))
Output:
<class 'set'>
Access value in a Set: We cannot access individual values in a set. We can only access all the elements
together.
x = {1, 2, 3, 4, 3, 2}
for i in x:
print(I,end=’ ‘)
Output: 1 2 3 4
x = {1, 3} Output:
x.add(2) {1, 2, 3}
print(x)
The only difference between the two is that the discard() function leaves a set unchanged if the
element is not present in the set. On the other hand, the remove() function will raise an error in such
a condition (if element is not present in the set).
x = {1, 3, 4, 5, 6} Output:
print(x) {1, 3, 4, 5, 6}
x.discard(4) {1, 3, 5, 6}
print(x)
{1, 3, 5}
x.remove(6)
print(x)
x.discard(2) {1, 3, 5}
print(x)
Traceback (most recent call last):
x.remove(2) File "<string>", line 28, in <module>
KeyError: 2
Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item will be popped.
We can also remove all the items from a set using the clear() method.
x = set("abcdefgh") Output:
print(x) {'d', 'c', 'b', 'a', 'f', 'h', 'e', 'g'}
print(x.pop()) d
print(x.pop()) c
Set Union: Union of A and B is a set of all elements from both sets.Union is performed using | operator.
Same can be accomplished using the union() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A | B) print(A.union(B))
print(B.union(A))
Output: Output:
{1, 2, 3, 4, 5, 6, 7, 8} {1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection: Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the intersection() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A & B) print(A.intersection(B))
print(B.intersection(A))
Output:
Output: {4, 5} {4, 5}
{4, 5}
Set Difference: Difference of the set B from set A(A - B) is a set of elements that are only in A but not
in B. Similarly, B - A is a set of elements in B but not in A. Difference is performed using - operator.
Same can be accomplished using the difference() method.
A = {1, 2, 3, 4, 5} A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8} B = {4, 5, 6, 7, 8}
print(A - B) print(A.difference(B))
print(B. difference (A))
print('p' not in x)
Iterating Through a Set: We can iterate through each item in a set using a for loop.
Example:
for letter in set("apple"): Output:
print(letter) a
p
l
e
Built-in Functions with Set
A = {1, 5, 3, 2, 4} Output:
print(len(A)) 5
print(min(A)) 1
print(max(A)) 5
print(sorted(A)) [1, 2, 3, 4, 5]
print(sum(A)) 15
Creating Python Dictionary: Creating a dictionary is as simple as placing items inside curly braces {}
separated by commas.
An item has a key and a corresponding value that is expressed as a pair (key: value). We can also create a
dictionary using the built-in dict() function.
x = {} Output
print(x) {}
print(x['name']) Dharmesh
print(x.get('rollno')) 1
print(x.get('address')) # Output None None
print(x['address']) # Trying to access keys which doesn't exist throws error Traceback (most recent
call last):
File "<string>", line 9,
in <module>
KeyError: 'address'
x['address'] = 'xyz' # adding value {'name': 'abc', 'rollno': 20, 'address': 'xyz'}
print(x)
Removing elements from Dictionary:
We can remove a particular item in a dictionary by using the pop() method. This method removes an
item with the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the
dictionary.
All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
del squares
print(squares) NameError: name
'squares' is not defined