PWeek # 3
PWeek # 3
Python Operators
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Program:
x=12
y=5
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(x%y)
print(x**y)
print(x//y)
OUTPUT:
17
7
60
2.4
2
248832
2
Python Assignment Operators
Assignment operators are used to assign values to variables:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
PROGRAM:
x=12
y=3
x+=y
print(x)
x-=y
print(x)
x*=y
print(x)
x/=y
print(x)
x%=y
print(x)
print("for every operation the values reintialized x=12 &
y =3")
x=12
y=3
x**=y
print(x)
x=12
y=3
x//=y
print(x)
x=12
y=3
x&=y
print(x)
x=12
y=3
x|=y
print(x)
x=12
y=3
x^=y
print(x)
x=12
y=3
x>>=y
print(x)
x=12
y=3
x<<=y
print(x)
OUTPUT:
15
12
36
12.0
0.0
1728
0
15
15
96
== Equal x == y
!= Not equal x != y
not Reverse the result, returns not(x < 5 and x < 10) Try it »
False if the result is true
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
Operator
Name Description Example Try it
& AND Sets each bit to 1 if both bits are x&y Try it »
1
Operator Precedence
Operator precedence describes the order in which operations are performed.
Example
Parentheses has the highest precedence, meaning that expressions inside
parentheses must be evaluated first:
print((6 + 3) - (6 + 3))
Run example »
Example
Multiplication * has higher precedence than addition +, and therefor
multiplications are evaluated before additions:
print(100 + 5 * 3)
Run example »
The precedence order is described in the table below, starting with the highest
precedence at the top:
() Parentheses Try it »
** Exponentiation Try it »
| Bitwise OR Try it »
or OR Try it »
If two operators have the same precedence, the expression is evaluated from
left to right.
Example
Addition + and subtraction - has the same precedence, and therefor we
evaluate the expression from left to right:
print(5 + 4 - 7 + 3)
output:
---------------------------------------------------------------------------------------
Python Lists
List
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.
Example
Create a List:
OUTPUT:
['apple', 'banana', 'cherry']
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the
list.
Note: There are some list methods that will change the order, but in general:
the order of the items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in
a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
OUTPUT
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
OUTPUT
<class 'list'>
<class 'list'>
<class 'list'>
Example
A list with strings, integers and boolean values:
print(type(list1))
OUTPUT:
<class 'list'>
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
Example
Using the list() constructor to make a List:
*Set items are unchangeable, but you can remove and/or add items whenever
you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Access Items
List items are indexed and you can access them by referring to the index
number:
Example
Print the second item of the list:
Try it Yourself »
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
Try it Yourself »
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 list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Try it Yourself »
Note: The search will start at index 2 (included) and end at index 5 (not
included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including,
"kiwi":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Try it Yourself »
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Try it Yourself »
Example
This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Try it Yourself »
Example
Check if "apple" is present in the list:
--------------------------------------------------------------------------------------------
Try it Yourself »
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
Try it Yourself »
If you insert more items than you replace, the new items will be inserted where
you specified, and the remaining items will move accordingly:
Example
Change the second value by replacing it with two new values:
Try it Yourself »
Note: The length of the list will change when the number of items inserted does
not match the number of items replaced.
If you insert less items than you replace, the new items will be inserted where
you specified, and the remaining items will move accordingly:
Example
Change the second and third value by replacing it with one value:
Try it Yourself »
Insert Items
To insert a new list item, without replacing any of the existing values, we can
use the insert() method.
Example
Insert "watermelon" as the third item:
-----------------------------------------------------------------------------
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Try it Yourself »
Insert Items
To insert a list item at a specified index, use the insert() method.
Example
Insert an item as the second position:
Try it Yourself »
Note: As a result of the examples above, the lists will now contain 4 items.
Extend List
To append elements from another list to the current list, use
the extend() method.
Example
Add the elements of tropical to thislist:
Try it Yourself »
Example
Add elements of a tuple to a list:
Try it Yourself »
------------------------------------------------------------------------------------------
Example
Remove "banana":
Try it Yourself »
If there are more than one item with the specified value, the remove() method
removes the first occurance:
Example
Remove the first occurance of "banana":
Try it Yourself »
Example
Remove the second item:
Try it Yourself »
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
Try it Yourself »
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Try it Yourself »
Example
Delete the entire list:
Try it Yourself »
Example
Clear the list content: