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

Introduction

The document provides an overview of Python programming, including its features, syntax, and basic data types such as numbers, strings, lists, tuples, and dictionaries. It emphasizes Python's simplicity and readability, making it a popular choice for beginners and its applications in various fields like machine learning and web development. Additionally, it introduces the use of Colab notebooks for interactive coding and collaboration.

Uploaded by

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

Introduction

The document provides an overview of Python programming, including its features, syntax, and basic data types such as numbers, strings, lists, tuples, and dictionaries. It emphasizes Python's simplicity and readability, making it a popular choice for beginners and its applications in various fields like machine learning and web development. Additionally, it introduces the use of Colab notebooks for interactive coding and collaboration.

Uploaded by

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

https://www.youtube.com/watch?

v=B7G5B8P8k9s&list=PL98qAXLA6afuh50qD2MdAj3ofYjZR_Phn

https://www.tutorialspoint.com/python/python_basic_syntax.htm

Chapter:1

Introduction, Features, Python building blocks – Identifiers, Keywords, Indention, Variables and
Comments,
Basic data types (Numeric, Boolean, Compound)
Operators: Arithmetic, comparison, relational, assignment, logical, bitwise, membership, identity
operators,
operator precedence
Control flow statements: Conditional statements (if, if…else, nested if)
Looping in Python (while loop, for loop, nested loops)
Loop manipulation using continue, pass, break.
Input/output Functions, Decorators, Iterators and Generators.

Version:Python 2.4.3
Python files have extension .py

Code: ITL404
Developed by Guido van Rossum
Why is it called Python? ... When he began implementing Python, Guido van Rossum was also
reading the published scripts
from “Monty Python's Flying Circus”, a BBC comedy series from the 1970s. Van Rossum
thought he needed a name that was
short, unique, and slightly mysterious, so he decided to call the language Python
----------------------------------------------------------------
*Python is a widely used high-level, general-purpose, interpreted, dynamic programming
language.
*Python is one of the easiest language to learn because of its easy syntax.
* It emphasizes code readability, and its syntax allows programmers to express concepts in
fewer lines of code than possible in languages
such as C++ or Java.
-----------------------------------------------------------------
The Structural Bioinformatics Library (SBL) is a Template C++/Python library for solving
structural biology problems.
The SBL provides programs (executables) for end-users and a rich framework todevelop novel
applications.
---------------------------------------------------------------
Features:
1. Simple and easy to understand
2.Python is freeware
C #.net is owned by microsoft
Java is owned by oracle
It means to use every library we need to pay as they are business making companies

But Python is maintained by a charitable foundation called Python software foundation( PFA)
hence free.
We dont need to pay for the software

3. Higher level Language like C,C++

4. Platform independent
Can run on windows, Linux OS, Ubuntu without any changes

5. Portable
Program can be transferred from one to other OS

6. Dynamically typed Language


7. Both procedure oriented and object oriented language

8. Interpreted Language
Code is executed line by line

9. Embedded
It means we can use it in any other web related program to develop any full fledge software
10. Extensive library
Like stdio.h,conio.h in C Python also have more libraries
----------------------------------------------------------------------------------------

Take a look at this prog in java

public class add_integers


{ public static void main(String args[])
{

System.out.println("Hello World");
}
}

In C language
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("Hello World");
getch();
}

Same code can be written in python as follows

print("Hello World")

The python prog is much more simple.


The simplicity of the program allows us to focus on logic, rather than the syntax of the program.
That's the reason, now in many
universities python is taught as the first programming language
Another reason to learn python is it is used in many areas like machine learning, web
development, data analysis, scientific research
automation and many more
It is used in many companies such as google, facebook, netflix and so on

Colaboratory, or "Colab" for short, allows you to write and execute Python in your browser, with

Zero configuration required


Free access to GPUs
Easy sharing

The document you are reading is not a static web page, but an interactive environment called a
Colab notebook that
lets you write and execute code.

Colab notebooks allow you to combine executable code and rich text in a single document,
along with images, HTML,
LaTeX and more. When you create your own Colab notebooks, they are stored in your Google
Drive account.
You can easily share your Colab notebooks with co-workers or friends, allowing them to
comment on your notebooks
or even edit them.

-------------------------------------------------------------------------------
Keywords

These are reserved words and you cannot use them as constant or variable or any other
identifier names.
All the Python keywords contain lowercase letters only.
eg: and exec not assert finally or if else etc
-----------------------------------------------------------------------------
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are part of the comment and the
Python interpreter
ignores them.

example: # First comment


print "Hello, Python!" # second comment

output: Hello, Python!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Multiline comments

Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments:

'''
This is a multiline
comment.
'''

----------------------------------------------------------------------------------
variables

Variables are nothing but reserved memory locations to store values.


This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals or
characters in these variables.
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically
when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator
is the value stored in the variable.

example:
a = 100 # An integer assignment
b = 1000.0 # A floating point
name = "John" # A string

print (a) or print("a=",a)


print(b) or print("b=",b)
print("name=", name)

---------------------------------------------------------------------------------------
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For
example −

a=b=c=1

Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables. For example −

a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object
with the value "john" is assigned to the variable c.

--------------------------------------------------------------------------------------
Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.

Python has five standard data types −


Numbers
String
List
Tuple
Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you
assign a value to them. For example −

var1 = 1
var2 = 10

You can delete a single object or multiple objects by using the del statement. For
example −

del var
del var_a, var_b

Python supports four different numerical types −

int (signed integers)


long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)

--------------------------------------------------------------------------------------------
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks.
Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.

However, Python does not have a character data type, a single character is simply a string with
a length of 1.

Square brackets can be used to access elements of the string.

example:
str = 'Hello World!'

print str # Prints complete string


print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
-------------------------------------------------------------------------------------------
Python Lists
A list contains items separated by commas and enclosed within square brackets ([]).
To some extent, lists are similar to arrays in C. One difference between them is that all the items
belonging to a
list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at
0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator,
and the asterisk (*) is the repetition operator.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator

example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
This produce the following result −

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

---------------------------------------------------------------------
Python Tuples
A tuple is another sequence data type that is similar to the list.
A tuple consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-only lists

example: tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print tuple # Prints the complete tuple


print tuple[0] # Prints first element of the tuple
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
print tuple[2:] # Prints elements of the tuple starting from 3rd element
print tinytuple * 2 # Prints the contents of the tuple twice
print tuple + tinytuple # Prints concatenated tuples
This produce the following result −

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
----------------------------------------------------------------------------------------------
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print dict['one'] # Prints value for 'one' key


print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among elements. It is incorrect to say that the elements
are "out of order";
they are simply unordered.
---------------------------------------------------------------------------------
Python Collections (Arrays)
There are four collection data types in the Python programming language:

1. List: is a collection which is ordered and changeable. Allows duplicate members.


2. Tuple: is a collection which is ordered and unchangeable. Allows duplicate members.
3. Set is a collection which is unordered and unindexed. No duplicate members.
4. Dictionary is a collection which is unordered and changeable. No duplicate members.

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.

Lists are created using square brackets:

Example
Create a List:

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


print(thislist)

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.

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:

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


print(thislist)

List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:

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


print(len(thislist))

List Items - Data Types


List items can be of any data type:

Example
String, int and boolean data types:

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


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:


Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

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?

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


print(type(mylist))

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:

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


print(list[1])

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:

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


print(thislist[-1])

------------------------------------------------------------------------------
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])
----------------------------------------------------------------------------------
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])
--------------------------------------------------------------------------------
Check if "apple" is present in the list:

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


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
--------------------------------------------------------------------------------
Change Item Value
To change the value of a specific item, refer to the index number:

Example
Change the second item:

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


thislist[1] = "blackcurrant"
print(thislist)
-------------------------------------------------------------------------------
Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values, and refer
to the range of index numbers where you want to insert the new values:

Example
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":

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


thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
-------------------------------------------------------------------------------
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:

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


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
------------------------------------------------------------------------------
Change the second and third value by replacing it with one value:

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


thislist[1:3] = ["watermelon"]
print(thislist)
------------------------------------------------------------------------
Insert Items
To insert a new list item, without replacing any of the existing values, we can use the insert()
method.

The insert() method inserts an item at the specified index:

Example
Insert "watermelon" as the third item:

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


thislist.insert(2, "watermelon")
print(thislist)
------------------------------------------------------------------------------------------
Append Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

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


thislist.append("orange")
print(thislist)
---------------------------------------------------------------------------
Insert Items
To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example
Insert an item as the second position:

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


thislist.insert(1, "orange")
print(thislist)
--------------------------------------------------------------------------
Extend List
To append elements from another list to the current list, use the extend() method.

Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
---------------------------------------------------------------------
Remove Specified Item
The remove() method removes the specified item.

Example
Remove "banana":

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


thislist.remove("banana")
print(thislist)
----------------------------------------------------------
Remove Specified Index
The pop() method removes the specified index.

Example
Remove the second item:

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


thislist.pop(1)
print(thislist)
---------------------------------------------------------
Example
Remove the last item:

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


thislist.pop()
print(thislist)
-----------------------------------------------------------
Remove the first item:

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


del thislist[0]
print(thislist)
----------------------------------------------------------
The del keyword can also delete the list completely.

Example
Delete the entire list:

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


del thislist
-------------------------------------------------------
Clear the List
The clear() method empties the list.

The list still remains, but it has no content.

Example
Clear the list content:

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


thislist.clear()
print(thislist)
-----------------------------------------------------------
tuples:

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


Tuple
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.

Example
Create a Tuple:

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


print(thistuple)

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 tuple are indexed, tuples can have items with the same value:

Example
Tuples allow duplicate values:

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


print(thistuple)

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

Example
Print the number of items in the tuple:

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


print(len(thistuple))

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.

Example
One item tuple, remember the commma:

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

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types


Tuple items can be of any data type:

Example
String, int and boolean data types:

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


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

A tuple can contain different data types:

Example
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'>
Example
What is the data type of a tuple?

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


print(type(mytuple))

Access Tuple Items


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

Example
Print the second item in the tuple:

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


print(thistuple[1])

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 tuple:

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


print(thistuple[-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.
Example
Return the third, fourth, and fifth item:

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


print(thistuple[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

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 included, "kiwi":

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


print(thistuple[:4])

Example
This example returns the items from "cherry" and to the end:

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


print(thistuple[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the tuple:

Example
This example returns the items from index -4 (included) to index -1 (excluded)

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


print(thistuple[-4:-1])

Check if Item Exists


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

Example
Check if "apple" is present in the tuple:

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


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Tuples are unchangeable, meaing that you cannot change, add, or remove items once the tuple
is created.

But there are some workarounds.

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.

Example
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)

Add Items
Once a tuple is created, you cannot add items to it.

Example
You cannot add items to a tuple:

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


thistuple.append("orange") # This will raise an error
print(thistuple)

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.

Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:

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


y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Remove Items
Note: You cannot remove items in a tuple.

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:

Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:

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


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Or you can delete the tuple completely:

Example
The del keyword can delete the tuple completely:

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


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:

Example
Packing a tuple:

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


But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking":

Example
Unpacking a tuple:

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

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)
Note: The number of variables must match the number of values in the tuple, if not, you must
use an asterix to
collect the remaining values as a list.

Using Asterix*
If the number of variables is less than the number of values, you can add an * to the variable
name and the values will be assigned to the variable as a list:

Example
Assign the rest of the values as a list called "red":

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

(green, yellow, *red) = fruits

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

If the asterix is added to another variable name than the last, Python will assign values to the
variable until the number of values left matches the number of variables left.

Example
Add a list of values the "tropic" variable:

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

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)

----------------------------------------------------------------------------------
Python Sets
myset = {"apple", "banana", "cherry"}
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 both unordered and unindexed.

Sets are written with curly brackets.

Example
Create a Set:

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


print(thisset)

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

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
Sets 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 add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.

Example
Duplicate values will be ignored:

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

print(thisset)

Get the Length of a Set


To determine how many items a set has, use the len() method.

Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Set Items - Data Types


Set items can be of any data type:

Example
String, int and boolean data types:

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


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

Example
A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}

type()
From Python's perspective, sets are defined as objects with the data type 'set':

<class 'set'>
Example
What is the data type of a set?

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


print(type(myset))

Access 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.

Example
Loop through the set, and print the values:

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

for x in thisset:
print(x)

Example
Check if "banana" is present in the set:

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

print("banana" in thisset)

Change Items
Once a set is created, you cannot change its items, but you can add new items.

Add 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.

Example
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, use the update() method.

Example
Add elements from tropical and thisset into newset:

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


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

thisset.update(tropical)

print(thisset)

Add Any Iterable


The object in the update() method does not have be a set, it can be any iterable object (tuples,
lists, dictionaries et,).
Example
Add elements of a list to at set:

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


mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Remove Item
To remove an item in a set, use the remove(), or the discard() method.

Example
Remove "banana" by using the remove() method:

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

thisset.remove("banana")

print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.

Example
Remove "banana" by using the discard() method:

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

thisset.discard("banana")

print(thisset)

You can also use the pop() method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed.

The return value of the pop() method is the removed item.

Example
Remove the last item by using the pop() method:

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


x = thisset.pop()

print(x)

print(thisset)

Note: Sets are unordered, so when using the pop() method, you do not know which item that
gets removed.

Example
The clear() method empties the set:

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

thisset.clear()

print(thisset)

Example
The del keyword will delete the set completely:

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

del thisset

print(thisset)
-------------------------------------------------------------------------------

Python Dictionaries

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and does not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered.

Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example
Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are
unordered.

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

Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Dictionary Length
To determine how many items a dictionary has, use the len() function:

Example
Print the number of items in the dictionary:

print(len(thisdict))

Dictionary Items - Data Types


The values in dictionary items can be of any data type:

Example
String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':

<class 'dict'>
Example
Print the data type of a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:

Example
Get the value of the "model" key:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

There is also a method called get() that will give you the same result:

Example
Get the value of the "model" key:

"year": 1964
}
x = thisdict["model"]
print(x)
x = thisdict.get("model")
print(x)

Get Keys
The keys() method will return a list of all the keys in the dictionary.

Example
Get a list of the keys:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary
will be reflected in the keys list.

Example
Add a new item to the original dictionary, and see that the value list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

print(car)

Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:
Example
Check if "model" is present in the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Update Dictionary
The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example
Update the "year" of the car by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Update Dictionary
The update() method will update the dictionary with the items from a given argument. If the item
does not exist, the item will be added.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example
Add a color item to the dictionary by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})

Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead):

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

Example
The del keyword removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

Example
The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a
reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Another way to make a copy is to use the built-in function dict().

Example
Make a copy of a dictionary with the dict() function:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:

myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)

child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

You might also like