0% found this document useful (0 votes)
16 views

Python-Basic-Elements

Uploaded by

Zeel Goyani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python-Basic-Elements

Uploaded by

Zeel Goyani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

Course Title: Programming with Python

Course Code: 202044504


Course Instructor: Ms. Jitiksha Patel

A. Y. : 2024-25
Python Programming
• Started as a hobby project by Guido Van Rossum and was first
released in 1991.
• An object-oriented programming construct language
• An open-source language
• A high-level language
• Uses an interpreter and hence called an interpreted language
• Supports minimalism and modularity to increase readability and
minimize time and space complexity
• Comes with a vast collection of libraries
• Python doesn’t convert its code into machine code
• Python converts the source code into a series of byte codes which is
stored with a .pyc or .pyo format.
• this byte code can’t be identified by CPU
• need for a mediator to do this task (Interpreter), In most PCs, Python
interpreter is installed at /usr/local/bin/python3.8.
• The python virtual machine To execute Bytecodes
Real World Applications
• Web Development- Django, Pyramid, Flask, and Bottle for developing web
frameworks
• Game Development- PySoy (a 3D game engine that supports Python 3)
and PyGame are two Python-based libraries used widely for game
development.
• Scientific and Numeric Applications-
• SciPy (scientific numeric library)
• Pandas (data analytics library)
• IPython (command shell)
• Numeric Python (fundamental numeric package)
• Natural Language Toolkit (Mathematical And text analysis)
• Artificial Intelligence and Machine Learning
• Language Development-many new programming languages such as Boo,
Swift, CoffeeScript, Cobra, and OCaml.
Real World Applications
• Desktop GUI- PyQt, PyGtk, Kivy, Tkinter, WxPython, PyGUI, and PySide are
some of the best Python-based GUI frameworks that allow developers to
create highly functional Graphical User Interfaces (GUIs)
• Software Development
• Enterprise-level/Business Applications
• Education programs and training courses
• Operating Systems
• Web Scraping Applications- BeautifulSoup, MechanicalSoup, Scrapy, LXML,
Python Requests, Selenium, and Urllib are some of the best Python-based
web scraping tools.
• Image Processing and Graphic Design Applications- Python is used in
several 3D animation packages such as Blender, Houdini, 3ds Max, Maya,
Cinema 4D, and Lightwave, to name a few.
Understanding code
Indentation matters to meaning the code
Block structure indicated by indentation
The first assignment to a variable creates it
Dynamic typing: no declarations, names don’t have types, objects
do
Assignment uses = and comparison uses ==
For numbers + - * / % are as expected.
Use of + for string concatenation.
Use of % for string formatting (like printf in C)
Logical operators are words (and,or,not) not symbols
The basic printing command is print
Whitespace
Whitespace is meaningful in Python, especially
indentation and placement of newlines
Use a newline to end a line of code
Use \n when must go to next line prematurely
No braces {} to mark blocks of code, use consistent
indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
Colons start of a new block in many constructs, e.g.
function definitions, then clauses
Comments
Start comments with #, rest of line is ignored
Can include a “documentation string” as the first line of
a new function or class you define
Development environments, debugger, and other tools
use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive
integer and returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Naming Rules
Names are case sensitive and cannot start with a
number. They can contain letters, numbers, and
underscores.
bob Bob _bob _2_bob_ bob_2 BoB
Keywords
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if, import,
in, is, lambda, not, or, pass, print,
raise, return, try, while
Data types
Literals
• In the following example, the parameter values passed to the print
function are all technically called literals
• More precisely, “Hello” and “Programming is fun!” are called textual literals,
while 3 and 2.3 are called numeric literals

>>> print("Hello")
Hello
>>> print("Programming is fun!")
Programming is fun!
>>> print(3)
3
>>> print(2.3)
2.3
Simple Assignment Statements
• A literal is used to indicate a specific value, which can be assigned to
a variable

>>> x = 2
 x is a variable and 2 is its value >>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements
• A literal is used to indicate a specific value, which can be assigned to
a variable

>>> x = 2
 x is a variable and 2 is its value >>> print(x)
2
 x can be assigned different values; >>> x = 2.3
hence, it is called a variable >>> print(x)
2.3
Simple Assignment Statements: Box View
• A simple way to view the effect of an assignment is to assume that
when a variable changes, its old value is replaced

>>> x = 2 x = 2.3
Before After
>>> print(x)
2 x 2 x 2.3
>>> x = 2.3
>>> print(x)
2.3
Simple Assignment Statements: Actual View
• Python assignment statements are actually slightly different from the
“variable as a box” model
• In Python, values may end up anywhere in memory, and variables are used to
refer to them
x = 2.3
>>> x = 2
Before After
>>> print(x) What will
2 2 happen to
x 2 x
>>> x = 2.3 value 2?
>>> print(x)
2.3
2.3
Garbage Collection
• Interestingly, as a Python programmer you do not have to worry about
computer memory getting filled up with old values when new values
are assigned to variables
After
Memory location
• Python will automatically clear old
values out of memory in a process x 2 X will be automatically
reclaimed by the
known as garbage collection garbage collector
2.3
Assigning Input
• So far, we have been using values specified by programmers and printed
or assigned to variables
• How can we let users (not programmers) input values?

• In Python, input is accomplished via an assignment statement


combined with a built-in function called input
<variable> = input(<prompt>)
• When Python encounters a call to input, it prints <prompt> (which is a
string literal) then pauses and waits for the user to type some text and
press the <Enter> key
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> name = input("Enter your name: ")


Enter your name: Mohammad Hammoud
>>> name
'Mohammad Hammoud'
>>>

• Notice that whatever the user types is then stored as a string


• What happens if the user inputs a number?
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> number = input("Enter a number: ")


Enter a number: 3
>>> number
Still a string! '3'
>>>

• How can we force an input number to be stored as a number and not as


a string?
• We can use the built-in eval function, which can be “wrapped around” the
input function
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a


number: "))
Enter a number: 3
>>> number
Now an int
3
(no single quotes)!
>>>
Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a


number: "))
Enter a number: 3.7
>>> number
And now a float
3.7
(no single quotes)!
>>>
Assigning Input
• Here is another sample interaction with the Python interpreter:

>>> number = eval(input("Enter an equation: "))


Enter an equation: 3 + 2
>>> number
5
>>>

The eval function will evaluate this formula and


return a value, which is then assigned to the variable “number”
Datatype Conversion
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
>>> number = int(input("Enter a number: "))
Enter a number: 3
>>> number
An integer
3
(no single quotes)!
>>>
Datatype Conversion
• Besides, we can convert the string output of the input function into an
integer or a float using the built-in int and float functions
>>> number = float(input("Enter a number: "))
Enter a number: 3.7
>>> number
A float
3.7
(no single quotes)!
>>>
Datatype Conversion
• As a matter of fact, we can do various kinds of conversions between
strings, integers and floats using the built-in int, float, and str functions
>>> x = 10 >>> y = "20" >>> z = 30.0
>>> float(x) >>> float(y) >>> int(z)
10.0 20.0 30
>>> str(x) >>> int(y) >>> str(z)
'10' 20 '30.0'
>>> >>> >>>

integer  float string  float float  integer


integer  string string  integer float  string
Simultaneous Assignment
• Python allows us also to assign multiple values to multiple variables all
at the same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
>>>

• This form of assignment might seem strange at first, but it can prove
remarkably useful (e.g., for swapping values)
Simultaneous Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)

>>> x = 2
>>> y = 3
>>> x = y
>>> y = x
>>> x X CANNOT be done with
two simple assignments
3
>>> y
3
Simultaneous Assignment
• Suppose you have two variables x and y, and you want to swap their
values (i.e., you want the value stored in x to be in y and vice versa)
>>> x = 2
Thus far, we have been using >>> y = 3
different names for >>> temp = x CAN be done with
variables. These names
are technically called
identifiers
>>> x = y
>>> y = temp  three simple assignments,
but more efficiently with
simultaneous assignment
>>> x
3
>>> y
2
>>>
Identifiers
• Python has some rules about how identifiers can be formed
• Every identifier must begin with a letter or underscore, which may be
followed by any sequence of letters, digits, or underscores
>>> x1 = 10
>>> x2 = 20
>>> y_effect = 1.5
>>> celsius = 32
>>> 2celsius
File "<stdin>", line 1
2celsius
^
SyntaxError: invalid syntax
Identifiers
• Python has some rules about how identifiers can be formed
• Identifiers are case-sensitive

>>> x = 10
>>> X = 5.7
>>> print(x)
10
>>> print(X)
5.7
Identifiers
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Python Keywords
Identifiers
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers

>>> for = 4
File "<stdin>", line 1
An example… for = 4
^
SyntaxError: invalid syntax
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
 This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
35
>>> print("5" + "7")
57
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
 This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
 This is another expression that uses the 35
multiplication operator >>> print("5" + "7")
57
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
 This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
 This is another expression that uses the 35
multiplication operator >>> print("5" + "7")
57
 This is yet another expression that uses the
addition operator but to concatenate (or glue)
strings together
Expressions
• You can produce new data (numeric or text) values in your program
using expressions

>>> x = 6 >>> print(x*y)


>>> y = 2 12
>>> print(x - y) >>> print(x**y)
Another 4 Yet another 36
example… >>> print(x/y) example… >>> print(x%y)
3.0 0
>>> print(x//y) >>> print(abs(-x))
3 6
Expressions: Summary of Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Float Division
** Exponentiation
abs() Absolute Value
// Integer Division
% Remainder

Python Built-In Numeric Operations


Integers
Integers are whole numbers. They have no fractional parts.
Integers can be positive or negative.
There are two types of integers in Python:
i) Integers(Signed) : It is the normal integer representation of
whole numbers using the digits 0 to 9. Python provides
single int data type to store any integer whether big or small.
It is signed representation i.e. it can be positive or negative.
ii) Boolean : These represent the truth values True and False. It
is a subtype of integers and Boolean values True and False
corresponds to values 1 and 0 respectively
Demonstration of Integer Data Type
#Demonstration of Integer-Addition of two integer number
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
sum=a+b
print("The sum of two integers=",sum)
Output:
Enter the value of a: 45
Enter the value of b: 67
The sum of two integers= 112
Floating point
A number having fractional part is a floating point number.
It has a decimal point. It is written in two forms :
i) Fractional Form : Normal decimal notation e.g. 675.456
ii) Exponent Notation: It has mantissa and exponent.
e.g. 6.75456E2
Advantage of Floating point numbers:
They can represent values between the integers.
They can represent a much greater range of values.
Disadvantage of Floating point numbers:
Floating-point operations are usually slower than integer operations.
#Demonstration of Float Number- Calculate Simple Interest
princ=float(input("Enter the Principal Amount:"))
rate=float(input("Enter the Rate of interest:"))
time=float(input("Enter the Time period:"))
si=(princ*rate*time)/100
print("The Simple Interest=",si)
Output:
Enter the Principal Amount:5000
Enter the Rate of interest:8.5
Enter the Time period:5.5
Simple Interest= 2337.5
Complex numbers

Python represents complex numbers in the form a+bj.


#Demonstration of Complex Number- Sum of two Complex
Numbers
a=7+8j
b=3.1+6j
c=a+b
print("Sum of two Complex Numbers")
print(a,"+",b,"=",c)
Output:
(7+8j) + (3.1+6j) = (10.1+14j)
Explicit and Implicit Data Type Conversion
• Data conversion can happen in two ways in Python
1. Explicit Data Conversion (we saw this earlier with the int, float, and str
built-in functions)

2. Implicit Data Conversion


• Takes place automatically during run time between ONLY numeric values
• E.g., Adding a float and an integer will automatically result in a float value
• E.g., Adding a string and an integer (or a float) will result in an error since
string is not numeric
• Applies type promotion to avoid loss of information
• Conversion goes from integer to float (e.g., upon adding a float and an
integer) and not vice versa so as the fractional part of the float is not lost
Implicit Data Type Conversion: Examples

>>> print(2 + 3.4)


 The result of an expression that involves
5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
>>> print(9/5 * 27 + 32)
80.6
>>> print(9//5 * 27 + 32)
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
Implicit Data Type Conversion: Examples

>>> print(2 + 3.4)


 The result of an expression that involves
5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
>>> print(9/5 * 27 + 32)
 The result of an expression that involves
80.6
values of the same data type will not result
>>> print(9//5 * 27 + 32)
in any conversion
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>
Modules
• One problem with entering code interactively into a Python shell is
that the definitions are lost when we quit the shell
• If we want to use these definitions again, we have to type them all over again!

• To this end, programs are usually created by typing definitions into a


separate file called a module or script
• This file is saved on disk so that it can be used over and over again

• A Python module file is just a text file with a .py extension, which can
be created using any program for editing text (e.g., notepad or vim)
Programming Environments and IDLE
• A special type of software known as a programming environment
simplifies the process of creating modules/programs

• A programming environment helps programmers write programs and


includes features such as automatic indenting, color highlighting, and
interactive development

• The standard Python distribution includes a programming


environment called IDLE that you can use for working on the
programs of this course
Summary
• Programs are composed of statements that are built from identifiers and
expressions

• Identifiers are names


• They begin with an underscore or letter which can be followed by a combination
of letter, digit, and/or underscore characters
• They are case sensitive

• Expressions are the fragments of a program that produce data


• They can be composed of literals, variables, and operators
Summary
• A literal is a representation of a specific value (e.g., 3 is a literal
representing the number three)

• A variable is an identifier that stores a value, which can change (hence,


the name variable)

• Operators are used to form and combine expressions into more complex
expressions (e.g., the expression x + 3 * y combines two expressions
together using the + and * operators)
Summary
• In Python, assignment of a value to a variable is done using the equal
sign (i.e., =)

• Using assignments, programs can get inputs from users and manipulate
them internally

• Python allows simultaneous assignments, which are useful for swapping


values of variables

• Datatype conversion involves converting implicitly and explicitly between


various datatypes, including integer, float, and string
Branching Programs

if Boolean expression:
block of code
else:
block of code
Example:
if x%2 == 0:
print(“Even”)
else:
print(“Odd”)
Print(“Done with conditional”)

Indentation is semantically meaningful in Python.


if x%2 == 0:
if x%3 == 0:
print(“Divisible by 2 and 3”)
else:
print(“Divisible by 2 and not by 3”)
elif x%3 == 0:
print(‘Divisible by 3 and not by 2”)
if x < y and x < z:
print(“x is least”)
elif y < z:
print(“y is least”)
else:
print(“z is least”)
Logical operators
Comparison operators
Bitwise operators
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Assignment operators
Python Numbers
• int, float and complex
• Examples:

a=5
print(a, "is of type", type(a))

a = 2.0 #A floating-point number is accurate up to 15 decimal places.


print(a, "is of type", type(a))

a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
• Python Program to Add Two Numbers
• Python Program to Calculate the Area of a Triangle
• Python Program to Swap Two Variables
• Python Program to Convert Kilometers to Meters
• Python Program to Check if a Number is Positive, Negative or 0
• Python Program to Check Leap Year
• Python Program to Check Prime Number
Lists:
• List items are:
• Ordered
• Changeable
• allow duplicate values
• Indexed
• List items can contain different data types.
Python List
• an ordered sequence of items
• All the items in a list do not need to be of the same type.
• Items separated by commas are enclosed within brackets [ ].
• Example:
a = [1, 2.2, 'python']
• The index starts from 0 in Python.
• Lists are mutable, meaning, the value of elements of a list can be
altered.
Slicing Operator ‘[ ]’
• to extract an item or a range of items from a list.
• Example:
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])
List Length
• len() function: To determine how many items a list has.
• Example:

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


print(len(fruits))
in keyword:
• To determine if a specified item is present in a list
• Example:
fruits = ["apple", "banana", "cherry"]

if "apple" in fruits:
print("Yes, 'apple' is in the fruits list")
insert() method
• The insert() method inserts an item at the specified index
• Syntax: list.insert(pos, elmnt)
• Example:
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)
print(odd)
append() method
• To add an item to the end of the list
• Example:
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
extend() method
• To append elements from another list to the current list
• We can add one item to a list using the append() method or add several
items using extend() method.
• Example:
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)

odd.extend([9, 11, 13])


print(odd)

odd.append([7,6])
print(odd)
• 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.
• Example:
# Concatenating and repeating lists
odd = [1, 3, 5]
print(odd + [9, 7, 5])
print(["re"] * 3)
remove() method
• removes the specified item.
• Example:

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


fruits.remove("banana")
print(fruits)
pop() method
• It removes the specified index.
• Example:
fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits)
• If you do not specify the index, the pop() method removes the last
item.
del keyword
• It removes the specified index
• Example:
fruits = ["apple", "banana", "cherry"]
del fruits[0]
print(fruits)
• It can also delete the list completely.
• Try: del fruits
clear() method
• It empties the list.
• The list still remains, but it has no content.
• Example:
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
for loop:
• The for loop in Python is used to iterate over a sequence or other
iterable objects.
• Iterating over a sequence is called traversal.
• Syntax:
for val in sequence: #val is the variable that takes the value of the item inside the sequence on each iteration.
Body of for
• Loop continues until we reach the last
item in the sequence.
• The body of for loop is separated from
the rest of the code using indentation.
• Example:
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

print("The sum is", sum)


• On each iteration or pass of the loop, a check is done to see if there
are still more items to be processed. If there are none left (this is
called the terminating condition of the loop), the loop has finished.
Program execution continues at the next statement after the loop
body.
• At the end of each execution of the body of the loop, Python returns
to the for statement, to see if there are more items to be handled.
• Example:

for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:


print("Hi ", name, " Please come to my party on Saturday!")
else:
print("No names left.")
The range() function
• We can generate a sequence of numbers using range() function.
• range(10) will generate numbers from 0 to 9 (10 numbers).
• Example:
x = range(6)
for n in x:
print(n)
• Syntax: range(start, stop, step_size)
• It returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Try by yourself:
• print(range(10))

• print(list(range(10)))

• print(list(range(2, 8)))

• print(list(range(2, 20, 3)))


• Example 1:
x = range(3, 6)
for n in x:
print(n)
• Example 2:
x = range(3, 20, 2)
for n in x:
print(n)
• We can use the range() function in for loops to iterate through a
sequence of numbers.
• It can be combined with the len() function to iterate through a
sequence using indexing.
Using Loop with Lists
• Example 1:
fruits = ["apple", "banana", "cherry"]
for x in fruits: #x will take values:
print(x)

• Example 2:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)): #i will take values:
print(fruits[i])
Test Your skills:
• Print First 10 natural numbers using for loop
• Python program to find the factorial of a number provided by the user.
• Print the following pattern:
1
12
123
1234
12345
• Program to print squares of all numbers present in a list
• Reverse the following list using for loop (Hint: Just print it in reverse order)
[1, 2, 3, 4, 5]
while loop:
• used to iterate over a block of code as long
as the test expression (condition) is true.
• Syntax:
while test_expression:
Body of while
• Example 1:
n = int(input("Enter n: "))
sum = 0 # initialize sum and counter
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum) # print the sum
• Example 2: (while loop with else)
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
break statement
• The break statement terminates
the loop containing it.
• If the break statement is inside a
nested loop (loop inside another
loop), the break statement will
terminate the innermost loop.
• Syntax: break
• Example:
for val in "string":
if val == "i":
break
print(val)

print("The end")
continue statement
• The continue statement is used to skip the
rest of the code inside a loop for the
current iteration only.
• Loop does not terminate but continues on
with the next iteration.
• Example:
for val in "string":
if val == "i":
continue
print(val)

print("The end")
Using a While Loop with list
• Example:
fruits = ["apple", "banana", "cherry"]
i=0
while i < len(fruits):
print(fruits[i])
i=i+1
sort() method
• sort the list alphanumerically, ascending, by default
• Example:
t = [100, 50, 65, 82, 23]
t.sort()
print(t)
• To sort descending, use the keyword argument reverse = True
• Example:
t = [100, 50, 65, 82, 23]
t.sort(reverse = True)
print(t)
reverse() Method
• method reverses the sorting order of the elements.

• Example:
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
Try yourself
• Copy a list from one to another.
• Make change in the first list.
• Example:
thislist = ["apple", "banana", "cherry"]
mylist = thislist
thislist[2]="bit"
print(mylist)
print(thislist)
• Example:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
thislist[2]="bit"
print(mylist)
print(thislist)
Copy method
• Make a copy of a list with the copy() method:
• Example:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
thislist[2]="bit"
print(mylist)
print(thislist)
Try yourself
• Join two Lists
• Append()
• Extend()
• + operator
• Example:
l1 = ["a", "b" , "c"]
l2 = [1, 2, 3]

for x in l2:
l1.append(x)

print(l1)
List Methods
Python Tuples
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Example:
fruits = ("apple", "banana", “apple")
print(fruits)
print(type(fruits))
Tuple Items
• Ordered - it means that the items have a defined order, and that
order will not change.
• Unchangeable - we cannot change, add or remove items after the
tuple has been created.
• allow duplicate values
• A tuple can contain different data types
• Example:
tuple1 = ("abc", 34, True, 40, "male")
• Example:
Fruits_tuple = ("apple", "banana", "cherry")
print(Fruit_tuple[1])
Access Tuple Elements
Indexing
Example 1:
Fruits_tuple = ("apple", "banana", "cherry")
print(Fruit_tuple[1])
Example 2:
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
• Negative Indexing: print(Fruit_tuple[-2])
• Slicing: print(Fruit_tuple[-2:-1])
• Check if Item Exists (using in keyword)
• Example 1:
t = ("apple", "banana", "cherry")
if "apple" in t:
print("Yes, 'apple' is in the fruits tuple")
Update Tuples
• You cannot add items to a tuple
• You can convert the tuple into a list, change the list/ add an item, and convert the
list back into a tuple.
• Example 1:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)
x = ("apple", "banana", "cherry")
print("x:",id(x))
y = list(x)
y[1] = "kiwi"
print("y:",id(y))
x = tuple(y)
print("x:",id(x))
print("y:",id(y))
• Example 2:
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9

# However, item of mutable element can be changed


my_tuple[3][0] = 9
print(my_tuple)

#try adding items in this list


Remove Items
• Example 1:
t = ("apple", "banana", "cherry")
y = list(t)
y.remove("apple")
t = tuple(y)
• you can delete the tuple completely
• Example 2:
del t
print(t)
• Try + and * operators:
• print((1, 2, 3) + (4, 5, 6))
• print(("Repeat",) * 3)
• Try below given code:
x = ("apple", "banana", "cherry“)
x=x+x
print(x)

x = ("apple", "banana", "cherry“)


x=x*x
print(x)
Tuple Methods
Test yourself
• Reverse the following tuple
a = (10, 20, 30, 40, 50)
• Access value 20 from the following tuple
a = ("Orange", [10, 20, 30], (5, 15, 25))
• Create a tuple with single item 10
• Swap the following two tuples
t1 = (1, 2)
t2 = (9, 8)
• Counts the number of occurrences of item 50 from a tuple
t1 = (50, 10, 60, 70, 50)
• List down the Advantages of Tuple over List

You might also like