0% found this document useful (0 votes)
120 views42 pages

Basic Session 2

Lists and tuples are ordered collections of items in Python. Lists are mutable and allow duplicates while tuples are immutable and also allow duplicates. Common list and tuple methods allow inserting, removing, looping and sorting their items.

Uploaded by

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

Basic Session 2

Lists and tuples are ordered collections of items in Python. Lists are mutable and allow duplicates while tuples are immutable and also allow duplicates. Common list and tuple methods allow inserting, removing, looping and sorting their items.

Uploaded by

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

Python Collections (Arrays)

• There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No
duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate
members.
Python Lists
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities
and usage.
• Lists are created using square brackets:
fruit= ["apple", "banana", "cherry"]
print(fruit)

• List items are ordered, changeable, and allow duplicate values.


• List items are indexed, the first item has index [0].
List Length
fruit= ["apple", "banana", "cherry"]
print( len(fruit) )

List Items - Data Types


list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list1 = ["abc", 34, True, 40, "male"]
The list() Constructor
fruit= list(("apple", "banana", "cherry")) # note the double round-brackets
print(fruit)

Python - Access List Items


fruit= ["apple", "banana", "cherry"]
print(fruit[1])
Negative Indexing
fruit= ["apple", "banana", "cherry"]
print(fruit[-1])

fruit= ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(fruit[2:5])

fruit = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(fruit[:4])

fruit = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(fruit[2:])

fruit = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(fruit[-4:-1])
Check if Item Exists
fruit= ["apple", "banana", "cherry"]
if "apple" in fruit:
print("Yes, 'apple' is in the a list")

fruit = [10,20,30,40,20,80]
if 15 in fruit:
print("yes")
else:
print("No")
Change List Items
fruit = ["apple", "banana", "cherry"]
fruit[1] = "blackcurrant"
print(fruit)

fruit = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


fruit[1:3] = ["blackcurrant", "watermelon"]
print(fruit)

fruit = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


fruit[1:3] = ["blackcurrant", "watermelon"]
print(fruit)

fruit = ["apple", "banana", "cherry"]


fruit[1:2] = ["blackcurrant", "watermelon"]
print(fruit)

fruit = ["apple", "banana", "cherry"]


fruit[1:3] = ["watermelon"]
print(fruit)
Insert Items
To insert a new list item at the end, without replacing any of the existing values.

fruit = ["apple", "banana", "cherry"]


fruit.append("orange")
print(fruit)

To insert a list item at a specified index


fruit = ["apple", "banana", "cherry"]
fruit.insert(2, "watermelon")
print(fruit)

To append elements from another list to the current list,


fruit= ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
fruit.extend(tropical)
print(fruit)
Remove List Items
fruit = ["apple", "banana", "cherry"]
fruit.remove("banana")
print(fruit)

Remove Specified Index


fruit = ["apple", "banana", "cherry"]
fruit = ["apple", "banana", "cherry"] fruit.pop()
fruit.pop(1) print(fruit)
print(fruit)

fruit = ["apple", "banana", "cherry"] fruit = ["apple", "banana", "cherry"]


del fruit[0] del fruit
print(fruit)

fruit = ["apple", "banana", "cherry"]


fruit.clear()
print(fruit)
Python - Loop Lists
Loop Through a List
fruit = ["apple", "banana", "cherry"]
for x in fruit:
print(x)

Loop Through the Index Numbers

fruit = ["apple", "banana", "cherry"]


for i in range(len(fruit)): //range(no)
print(fruit[i])

Using a While Loop


fruit = ["apple", "banana", "cherry"]
i = 0
while i < len(fruit):
print(fruit[i]) fruit = ["apple", "banana", "cherry"]
i = i + 1 [print(x) for x in fruit]
List Comprehension
fruit = ["apple", "banana", "cherry"]
[print(x) for x in fruit]

a = ["apple", "banana", "cherry", "kiwi", "mango"]


b = []

for x in a:
// if "a" in x:
b.append(x)

print(b)
Condition
a = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in a if x != "apple"]
print(newlist)

Iterable
newlist = [x for x in range(10)]
print(newlist)

newlist = [x for x in range(10) if x < 5]


print(newlist)
Expression
a = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x.upper() for x in a]


print(newlist)

newlist = ['hello' for x in a]

newlist = [x if x != "banana" else "orange" for x in a]


Sort Lists
fruit = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruit.sort()
print(fruit)

marks = [100, 50, 65, 82, 23]


marks.sort()
print(marks)

Sort Descending
fruit = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruit.sort(reverse = True)
print(fruit)

Reverse Order
fruit = ["banana", "Orange", "Kiwi", "cherry"]
fruit.reverse()
print(fruit)
fruit = ["banana", "Orange", "Kiwi", "cherry"]
fruit.sort(key = str.lower)
print(fruit)
Copy Lists

fruit = ["apple", "banana", "cherry"]


mylist = fruit.copy()
print(mylist)

fruit = ["apple", "banana", "cherry"]


mylist = list(fruit)
print(mylist)
Join Lists
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

list1 = ["a", "b" , "c"] list1 = ["a", "b" , "c"]


list2 = [1, 2, 3] list2 = [1, 2, 3]
for x in list2: list1.extend(list2)
list1.append(1) print(list1)
print(list1)
List Methods

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python Tuples
• Tuples are used to store multiple items in a single variable.
• Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Set, and Dictionary, all with different qualities and usage.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Tuple items are ordered, unchangeable, and allow duplicate values.

a= ("apple", "banana", "cherry")


print(a)

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

tuple1 = ("abc", 34, True, 40, "male") mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:

a = ("apple", "banana", "cherry", "apple", "cherry")


print(a)
Tuple Length
To determine how many items a tuple has, use the len() function:

a = ("apple", "banana", "cherry")


print(len(a))

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a
tuple.

a = ("apple",)
print(type(a))

#NOT a tuple
a = ("apple")
print(type(a))
Tuple Items - Data Types
Tuple items can be of any data type:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple with strings, integers and boolean values:


tuple1 = ("abc", 34, True, 40, "male")

type()

From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>

a = ("apple", "banana", "cherry")


print(type(a))
Python - Access Tuple Items

Access Tuple Items


You can access tuple items by referring to the index number inside square brackets:

Print the second item in the tuple:


a = ("apple", "banana", "cherry")
print(a[1])

Negative Indexing

Negative indexing means start from the end.


-1 refers to the last item, -2 refers to the second last item etc.

Print the last item of the tuple:


a = ("apple", "banana", "cherry")
print(a[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.

Return the third, fourth, and fifth item:

a = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(a[2:5])

a = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(a[:4])

a = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(a[2:])

a = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(a[-4:-1])
Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword:


Check if "apple" is present in the tuple:

a = ("apple", "banana", "cherry")


if "apple" in a:
print("Yes, 'apple' is in the fruits tuple")
Python - Update Tuples

Change Tuple Values


• Once a tuple is created, you cannot change its values.
• Tuples are unchangeable, or immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.

Convert the tuple into a list to be able to change it:


x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x) //Output: ("apple", "kiwi", "cherry")


Add Items
• Since tuples are immutable, they do not have a build-in append() method, but there are other
ways to add items to a tuple.
1. Convert into a list:
Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and
convert it back into a tuple.
tp = ("apple", "banana", "cherry")
y = list(tp)

y.append("orange")
tp = tuple(y)

2. Add tuple to a tuple.


You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new
tuple with the item(s), and add it to the existing tuple:

Create a new tuple with the value "orange", and add that tuple:
tp = ("apple", "banana", "cherry")
y = ("orange",)
tp += y

print(tp)
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
tp = ("apple", "banana", "cherry")
y = list(tp)

y.remove("apple")
tp = tuple(y)

The del keyword can delete the tuple completely:


tp = ("apple", "banana", "cherry")
del tp
print(tp) #this will raise an error because the tuple no longer exists
a = ("apple", "banana", "cherry")
Unpacking a Tuple
(green, yellow, red) = a

print(green)
print(yellow)
print(red)

a = ("apple", "banana", "cherry", "strawberry", "raspberry")


Using Asterisk*
If the number of variables is (green, yellow, *red) = a
less than the number of
values, you can add an * to print(green) apple
the variable name and the print(yellow) banana
values will be assigned to print(red) ['cherry', 'strawberry', 'raspberry']
the variable as a list:

a = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = a

print(green)
print(tropic) apple
['mango', 'papaya', 'pineapple']
print(red)
cherry
Python - Loop Tuples
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Iterate through the items and print the values:

tp = ("apple", "banana", "cherry")


for x in tp:
print(x)

Loop Through the Index Numbers


You can also loop through the tuple items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.

Print all items by referring to their index number:

tp = ("apple", "banana", "cherry")


for i in range(len(tp)):
print(tp[i])
Using a While Loop
• You can loop through the list items by using a while loop.
• Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by
refering to their indexes.
• Remember to increase the index by 1 after each iteration.

Print all items, using a while loop to go through all the index numbers:
tp = ("apple", "banana", "cherry")
i = 0
while i < len(tp):
print(tp[i])
i = i + 1
Python - Join Tuples
Join Two Tuples
To join two or more tuples you can use the + operator:
Join two tuples:

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3) ('a', 'b', 'c', 1, 2, 3)
('a', 'b', 'c', 1, 2, 3)

Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use the * operator:
Multiply the fruits tuple by 2:

fruits = ("apple", "banana", "cherry")


mytuple = fruits * 2

print(mytuple) ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')


Python - Tuple Methods

Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was
found
Set
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• Not allowed duplicate

set1 = {"apple", "banana", "cherry"}


print(set1)

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values .

Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.

Duplicate values will be ignored:


t = {"apple", "banana", "cherry", "apple"}

print(thisset)
Get the Length of a Set
To determine how many items a set has, use the len() function.

st = {"apple", "banana", "cherry"}


print(len(st))

Set Items - Data Types


Set items can be of any data type:
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False} set1 = {"abc", 34, True, 40, "male"}

type()
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
The set() Constructor
It is also possible to use the set() constructor to make a set.

Using the set() constructor to make a set:

s = set(("apple", "banana", "cherry")) # note the double round-brackets


print(s)

Python - Access Set Items


You cannot access items in a set by referring to an index or a key.
But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using
the in keyword.

Loop through the set, and print the values:

st = {"apple", "banana", "cherry"}

for x in st:
print(x)

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)
Add Set Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.

Add an item to a set, using the add() method:


thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)
Add Sets
To add items from another set into the current set

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical) The del keyword will delete the set completely:


thisset = {"apple", "banana", "cherry"}
print(thisset) del thisset
print(thisset)
Remove the last item by using the pop() method:
Remove Item
thisset = {"apple", "banana", "cherry"}
thisset = {"apple", "banana", "cherry"} print(thisset)
thisset.remove("banana") x = thisset.pop()
print(thisset) print(x)
print(thisset)
thisset = {"apple", "banana", "cherry"} The clear() method empties the set:
thisset.discard("banana") thisset = {"apple", "banana", "cherry"}
print(thisset) thisset.clear()
print(thisset)
Loop Items
You can loop through the set items by using a for loop:
Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Join Two Sets


There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or
the update() method that inserts all the items from one set into another:

The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)
Set Methods
Python has a set of built-in methods that you can use on sets.

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others

You might also like