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

U1L678 Python

Uploaded by

shubhpatidar227
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)
13 views33 pages

U1L678 Python

Uploaded by

shubhpatidar227
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/ 33

Data types: Lists, Sets

and Tuples
Unit 1, Lesson 6
Lists: Understanding List Creation
List is a data type of Python used to store
multiple values of different types of data at
a time. List are represented with [].

A list can be created by putting comma


separated values between square
brackets []
Accessing items in a List
Values stored in the list are accessed using an index.

Index range between 0 to n-1, where n is the number of


values in the list

Python allows negative indexing for lists. The index of -


1 refers to the last value of the list, -2 refers to
the second last value of the list and so on.
Accessing Values in Lists: A value at a particular index
in a list is accessed using listname[index]
Printing List
Printing lists: The lists can be printed using the built-in
function print()
Slicing of List
Slicing lists: Slicing is used to access a subset of of a
list. For a list l = [1, 4, 5, 7, 4, 15], a subset of list from 2nd
index to 3rd index is obtained by l[2:4] which is equal
to [5,7]. Slicing can be understood using the following
examples:
Concatenating, Repeating Lists
Concatenating lists: We can concatenate two lists
using (+) operator.
Repeating lists: We can print a list multiple times using
(*) operator as shown below.
Nested Lists
• Working with nested lists: The items of the list can
be lists themselves, which means that the lists can be
nested.
Operations on Lists
Unlike strings, lists are mutable i.e. we can modify the
list (change the items, add items and reassign an item).

The following operations can be performed on the list :

1. Modify or reassign an item present at a particular


index
2. Add an item to the list at a particular index. (append,
extend)
3. Remove an item from the list.(remove, pop, clear)
Set
• A set is a mutable data type that contains
an unordered collection of items. A set is represented
with { }.
• Every element in the set should be unique (no
duplicates) and must be immutable (which cannot be
changed). But the set itself is mutable. We
can add or remove items / elements from it.
Uses of Set

The main uses of sets are:


• Membership testing
• Removing duplicates from a sequence
• Performing mathematical operations such as
intersection, union, difference, and symmetric
difference
tuple
• A tuple in Python is similar to a list, but with important
distinctions:
• Lists are enclosed in square brackets [], and their
elements and size can change (mutable). Tuples are
enclosed in parentheses () and are unchangeable
(immutable).
• Tuples are similar as read-only lists, providing a
performance advantage during iteration due to their
immutability.
• Once defined, you can't add or remove elements from a
tuple.
Creating a tuple
• Creating a tuple:
• Use the built-in tuple() function.
• An empty tuple can be created with tuple1 = tuple().
• Tuples can be defined by placing items within
parentheses, separated by commas.
• The parentheses are optional but it is a good practice to
write them.
• A one-element tuple must require a trailing comma,
like (1,).
• Be cautious with single-element tuples:
• (1) is interpreted as an integer, not a tuple. Use (1,) for a one-
Multi element tuples
• Multiple-element tuples:
• Trailing commas in multiple-element tuples are optional.
• Multiple-element tuple looks like this:
• (1, 2, 3) or 1, 2, 3
• (or)
• (1, 2, 3,) or 1, 2,
Data types:
Dictionaries
Unit 1, Lesson 7
What are dictionaries ?
• Dictionary is an unordered collection
of key and value pairs.
• General usage of dictionaries is to store key-value pairs
like Employees and their wages, Countries and their
capitals, Commodities and their prices etc.
• In a dictionary, the keys should be unique, but the
values can be similar.
• Keys of the dictionary cannot be changed.
Dictionary is a Python data type to store multiple values.
What are dictionaries ?
• Immutable data types like number, string, tuple etc.
are used for the key and any data type is used for
the value.
• Dictionaries are optimized to retrieve values when the
keys are known.
• Dictionaries are represented using key-value pairs
separated by commas inside curly braces {}.
• The key-value pairs are represented as key : value.
• For example:, daily temperatures in major cities are
mapped into a dictionary as { "Hyderabad" : 27 ,
"Chennai" : 32 , "Mumbai" : 40 }.
How to create them ?
• Note: While other compound data types (like lists,
tuples and sets) have only value as an element, a
dictionary has a key : value pair
• Creating a dictionary:
A dictionary can be created Afollows
indictionary
two:
with elements can be created as
ways.
mydict = dict("Hyderabad" : 20,
1. Using built-in dict() function.
"Delhi" : 30)
An empty dictionary can be created as follows :
mydict = dict()
# Creating an empty dictionary called mydict
print(type(mydict))
# Result: <class 'dict’>
print(mydict) # Result: {}
Keys are unchangeable ! , Lets get
the values.
• Keys of the dictionary cannot be changed.
1. Creating a dictionary:
dict1 = {"name":"Jay", "number":514, "age":12}
print(dict1)
#Result : {"name":"Jay", "number":514, "age":12}
2. Let us retrieve the values using their keys as index:
print(dict1['age']) # using key called 'age', we can get value 12
print(dict1['number']) # using key called 'number', we can get value 514
3. Let us find what happens when we try to retrieve an element
(key) which is not present in the dictionary:
print(dict1['place']) #Results in KeyError as there is no key 'place' in the
dictionary.
If the key is not there in the dictionary, we get a KeyError .
No numerical index please !
• We cannot use a numerical index (as in lists, tuples and
strings) to access the items/elements of the dictionaries
as dictionaries are unordered
• (Imagine all the items of a dictionary are put in a bag and
jumbled, so there is no order and we cannot retrieve the items
using a sequential index.)
The other way to access values :
get(“Key”)
Using the get() method.

capitals = {"U.S.A": "Washington D.C", "India": "New Delhi", "Nepal":


"Kathmandu"}

print(capitals.get("India")) # Printing the value with the key "India" i.e.


"New Delhi".

Trying to access a key that is not present in the dictionary using the get()
method results in None

capitals = {"U.S.A": "Washington D.C", "India": "New Delhi", "Nepal":


"Kathmandu"} print(capitals.get("Australia")) # Since the key "Australia" is
not present, it results in a "None"
Data type conversion
Converting data of one type to data of another type is
called Type Conversion.
Python defines various type conversion functions.
• 1. int(x, base): This function converts x to an integer of the
specified base, the default x value is 0. If the base is not
specified, it defaults to 10.
• 2. float(x): This function is used to convert any data type to a
floating point number. The float() function returns a floating
point number from a number or a string.
Infinity, nan and other strings
Data type conversion: ord, hex, oct
and complex
• ord(‘c’): The ord(‘x’) method returns an integer
representing a Unicode code point for the given Unicode
character.
• hex(i): The hex() function converts an integer to its
corresponding hexadecimal string.
oct(i): The oct() method takes an integer and returns its
octal representation.
• complex(real, imag): The complex() method returns a
complex number when the real and imaginary parts are
provided, or it converts a string to a complex number.
It is complex
Data type conversion: str, eval and
chr
• str(x): The str() function is used to convert x to a string representation.

• eval(str): The eval() method parses the expression passed to this


method and runs python expression (code) within the program.

• chr(): The chr() method returns a character (a string) from an integer


(that represents unicode code point of the character). This is the
inverse of ord() function.
• If the value is outside the range of (0 , 1114111), it results in a ValueError:
chr() arg not in range(0x110000).
Input and output
statements
Unit 1, Lesson 8
Reading input in python
• value = Input([prompt])
• Here the optional prompt string will be printed to the console for the user to
input a value
• By default the input is taken as a string, however, you can convert the
convertible input to int or float using int() or float() methods.
• ivalue = int(Input([prompt])
• fvalue = float(input([prompt])
%formatting and str.format function
• The print() method is used to print the values to the standard output

• Output Formatting in Python


• Python uses C-style string formatting to create new, formatted strings.
The % operator also called as 'string modulo operator' is used to
format a set of variables enclosed in a "tuple" (a fixed size list), together
with a format string, which contains normal text together with
"argument specifiers", special symbols like %s and %d.
The general syntax for a format placeholder is:
%[flags][width][.precision]type

The following are some basic argument


specifiers:
•%s - String (or any object with a string representation,
like numbers)
•%d - Integers
• %f - Floating point numbers
• %.<number of digits>f - Floating point numbers with a
fixed amount of digits for the decimal part.
• %x or %X - Integers in hexadecimal representation
(uppercase/lowercase)
• %o - Octal representation
Example 1: If we consider a single variable
called 'name' with a username in it, and if we would
like to print a greeting to that user, then:
name = "Ravi"
print("Good morning, %s!" % name)
# This statement prints "Good morning, Ravi!" Output:
Good morning, Ravi!
Example 2: If we consider more than one variable, we must
use a tuple of those variables as shown below :
a = 10
b = 20
str = "Hello"
print("The value of a = %d, b = %d and str = %s" %(a, b, str))
Output: The value of a = 10, b = 20 and str = Hello
Some more examples
str.format
• The output can also be presented in a more elegant way
using the str.format()

This style of string formatting eliminates the usage


of % operator (string modulo operator).

The general syntax of str.format() function is:


{}{}.format(value1, value2,...,valuen)
str.format()
• The following are some basic argument specifiers
used with str.format():
• {} - String (or any object with a string representation,
like numbers)
• {0:<number of digits>d} - Integers
• {0:.<number of digits>f} - Floating point numbers with
a fixed amount of digits for the decimal part.
• {0:X} or {0:x} - Integers in hex representation
(uppercase/lowercase)
• {0:o} - Octal representation

You might also like