0% found this document useful (0 votes)
13 views31 pages

Py Slides 4

The document provides an overview of Python's data types including lists, tuples, and sets, detailing their properties, methods, and operations. It explains how to create, access, update, and delete elements in these data types, along with examples for clarity. Additionally, it covers advanced features like list comprehensions and frozen sets, emphasizing the differences between mutable and immutable types.

Uploaded by

babycoder143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views31 pages

Py Slides 4

The document provides an overview of Python's data types including lists, tuples, and sets, detailing their properties, methods, and operations. It explains how to create, access, update, and delete elements in these data types, along with examples for clarity. Additionally, it covers advanced features like list comprehensions and frozen sets, emphasizing the differences between mutable and immutable types.

Uploaded by

babycoder143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

10.

Python - 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.
• Good thing about a list that items in a list need not all
have the same type:
• For example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

Like string indices, list indices start at 0, and lists can be


sliced, concatenated and so on.
Accessing Values in Lists:
• To access values in lists, use the square brackets for slicing
along with the index or indices to obtain value available at
that index:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
• This will produce following result:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Adding Values in Lists

• To add an item to the end of the list, use the

• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
Print(list1))
list1.append(“Maths")
print “After adding New value list is: "
Print(list1))
This will produce following result:
['physics', 'chemistry', 1997, 2000]
After adding New value list is:
['physics', 'chemistry', 1997, 2000,’Maths’]
Updating Lists:
• You can update single or multiple elements of lists by giving
the slice on the left-hand side of the assignment operator, and
you can add to elements in a list with the append() method:
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list1[2];
list1[2] = 2001;
print "New value available at index 2 : "
print list1[2];
• This will produce following result:
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements:
• To remove a list element, you can use either the del
statement if you know exactly which element(s) you are
deleting or the remove() method if you do not know.
• Example:
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
• This will produce following result:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
list1 = ['physics', 'chemistry', 1997, 2000];
print list1;
List1.remove(1997);
print "After deleting an element : "
print list1;

• This will produce following result:


['physics', 'chemistry', 1997, 2000]
After deleting value an element:
['physics', 'chemistry', 2000]
Loop Through a List

• You can loop through the list items by using a for loop

• thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)
• Print all items in the list, one by one:
• Loop Through the Index Numbers
• thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
Using a While Loop

• thislist = ["apple", "banana", "cherry"]


i=0
while i < len(thislist):
print(thislist[i])
i=i+1
Looping Using List Comprehension

• List Comprehension offers the shortest


syntax for looping through lists:

• thislist = ["apple", "banana", "cherry"]


[print(x) for x in thislist]
Basic 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.
• In fact, lists respond to all of the general sequence operations we
used on strings in the prior chapter :

Python Expression Results Description


len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] TRUE Membership

for x in [1, 2, 3]: print x, 123 Iteration


Indexing, Slicing, and
Matrixes:
• Because lists are sequences, indexing and slicing work the same way
for lists as they do for strings.
• Assuming following input:
L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description


L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from


the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
List Methods:

SN Function Description
1 append() Adds an element at the end of
the list
2 clear() Removes all the elements from
the list
3 copy() Returns a copy of the list
4 count() Returns the number of
elements with the specified
value
5 extend() Add the elements of a list (or
any iterable), to the end of the
current list
S
Methods with Description
N
1 index() Returns the index of the first
element with the specified value

2 insert() Adds an element at the specified


position

3 pop() Removes the element at the


specified position

4 remove() Removes the item with the


specified value

5 reverse() Reverses the order of the list

6 sort() Sorts the list


11. Python - Tuples
• A tuple is a sequence of immutable Python objects. Tuples are
sequences, just like lists. The only difference is that tuples can't be
changed ie. tuples are immutable and tuples use parentheses and
lists use square brackets.
• Creating a tuple is as simple as putting different comma-separated
values and optionally you can put these comma-separated values
between parentheses also. For example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing:
tup1 = ();
To write a tuple containing a single value you have to include a
comma, even though there is only one value:
tup1 = (50,);
• Like string indices, tuple indices start at 0, and tuples can be sliced,
concatenated and so on.
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]
print "tup2[1:5]: “, tup2[1:5]
• This will produce following result:
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples:
• Tuples are immutable which means you cannot update
them or change values of tuple elements. But we able able
to take portions of an existing tuples to create a new tuples
as follows:
• Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
tup3 = tup1 + tup2;
print tup3;
This will produce following result:
(12, 34.56, 'abc', 'xyz')
Delete Tuple Elements:
• Removing individual tuple elements is not possible. There
is, of course, nothing wrong with putting together another
tuple with the undesired elements discarded.
• To explicitly remove an entire tuple, just use the del
statement:
• Example:
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : " print tup;
• This will produce following result.
('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
Basic Tuples Operations:
• Tuples respond to the + and * operators much like strings;
they mean concatenation and repetition here too, except
that the result is a new tuple, not a string.
• In fact, tuples respond to all of the general sequence
operations we used on strings in the prior chapter :

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
['Hi!'] * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) TRUE Membership
for x in (1, 2, 3): print 1 2 3 Iteration
x,
Indexing, Slicing, and
Matrixes:
• Because tuples are sequences, indexing and slicing work
the same way for tuples as they do for strings.
• Assuming following input:
L = ('spam', 'Spam', 'SPAM!')
Python
Results Description
Expression
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Built-in Tuple Functions:

SN Function with Description


1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
• tuple1, tuple2 = (123, 'xyz'), (456, 'abc')
print cmp(tuple1, tuple2)
• print cmp(tuple2, tuple1)
• tuple3 = tuple2 + (786,);
• print cmp(tuple2, tuple3)
12. Python - SET
• In Python, a set is an unordered collection of unique
elements. Unlike lists or tuples, sets do not allow duplicate
values.
• Sets are mutable, meaning you can add or remove items
after a set has been created.
• Sets are defined using curly braces {} or the built-
in set() function
Creating a Set in Python

• Using Curly Braces


my_set = {1, 2, 3, 4, 5} print (my_set)
It will produce the following result −
{1,2,3,4,5}

• Using the set() Function


• my_set = set([1, 2, 3, 4, 5]) print (my_set)

It will produce the following result −


{1,2,3,4,5}
Duplicate Elements in Set

• If you try to create a set with duplicate elements,


duplicates will be automatically removed −

• my_set = {1, 2, 2, 3, 3, 4, 5, 5} print


(my_set)

• The result obtained is as shown below −


• {1,2,3,4,5}

• mixed_set = {1, 'hello', (1, 2, 3)}


• print (mixed_set)
Adding Elements in a Set

• To add an element to a set, you can use the add() function.

• my_set = {1, 2, 3, 3}
• # Adding an element 4 to the set
my_set.add(4)
• print (my_set)

• Following is the output obtained −


• {1, 2, 3,4}
Removing Elements from a Set

• my_set = {1, 2, 3, 4}
• # Removes the element 3 from the set
• my_set.remove(3)
• print (my_set)

• The output displayed is as shown below −


• {1, 2, 4}
• Alternatively, you can use the discard() function to
remove an element from the set if it is present. Unlike
remove(), discard() does not raise an error if the element is
not found in the set −
Membership Testing in a Set

• my_set = {1, 2, 3, 4}
• if 2 in my_set:
• print("2 is present in the set")
• else:
• print("2 is not present in the set")
• Following is the output of the above code

• 2 is present in the set
Set Operations

• Union − It combine elements from both sets using the


union() function or the | operator.

• Intersection − It is used to get common elements using


the intersection() function or the & operator.

• Difference − It is used to get elements that are in one set


but not the other using the difference() function or
the - operator.

• Symmetric Difference − It is used to get elements that


are in either of the sets but not in both using the
symmetric_difference() method or the ^ operator.
Python Set Comprehensions

• Set comprehensions in Python is a concise way to create sets


based on iterable objects, similar to list comprehensions. It is
used to generate sets by applying an expression to each item
in an iterable.
• Set comprehensions are useful when you need to create a set
from the result of applying some operation or filtering
elements from another iterable.
• set_variable = {expression for item in
iterable if condition}
• squared_set = {x**2 for x in range(1, 6)}
print(squared_set)
• The output obtained is as follows −
• {1,4,9,16,25}
Filtering Elements Using Set
Comprehensions

• even_set = {x for x in range(1, 11) if x % 2 ==


0}
• print(even_set)

• This will produce the following output −

• {2,4,6,8,10}
Frozen Sets

• In Python, a frozen set is an immutable collection of unique


elements, similar to a regular set but with the distinction
that it cannot be modified after creation. Once created, the
elements within a frozen set cannot be added, removed, or
modified, making it a suitable choice when you need an
immutable set.

• my_frozen_set = frozenset([1, 2, 3])


print(my_frozen_set)
• my_frozen_set.add(4)
• Following is the output of the above code −
• Gives error

You might also like