0% found this document useful (0 votes)
21 views45 pages

Datatypes

Uploaded by

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

Datatypes

Uploaded by

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

PYTHON DATA TYPES

• Built-in Data Types


• Python has the following data types built-in by default, in these
categories:
Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

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

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

x = range(6) range

x = {"name" : "John", "age" : 36 dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType
You can get the data type of any object using the type() function:
Example:
Print the data type of the variable x:
x = 5
print(type(x))
In Python, the data type is set when you assign a value to a variable:
TASK
• x=5
• Print type(x)
1. NUMERIC
• Numeric values are stored in numbers. The whole number, float, and complex qualities have a
place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type.
• There are three numeric types in Python:
•int
•float
•complex
• Variables of numeric types are created when you assign a
value to them:
•x = 1 # int
y = 2.8 # float
z = 1j # complex
• Int
• Int, or integer, is a whole number of unlimited length, positive or negative,
without decimals.
• Float
• Float, or "floating point number" is a number, positive or negative, containing
one or more decimals.
• Complex
• Complex numbers are written with a "j" as the imaginary part:
• You can convert from one type to another with
the int(), float(), and complex() methods
• x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))

• Python does not have a random() function to make a random
number, but Python has a built-in module called random that
can be used to make random numbers

• Example
• Import the random module, and display a random number between 1 and 9:

• import random
print(random.randrange(1, 10))

LAB
• Write a program to demonstrate different number data types in python.
Sequence Type
• In Python, sequence is the ordered collection of similar or different data types.
• Sequence data types in programming languages like Python include strings, lists,
and tuples. These types share several key characteristics:
• 1. Ordered: The elements in a sequence have a specific order, and each element
can be indexed and accessed based on its position within the sequence.
• 2. Indexable: Elements in a sequence can be accessed using indices. In Python,
indices start at 0 for the first element and go up to n-1 for a sequence of length n.
• 3. Slicable: Subsets of the sequence can be accessed using slicing. This allows for
extracting a part of the sequence by specifying a range of indices.
• 4. Iterable: Sequences can be iterated over using loops (e.g., for loops), allowing
for processing each element in the sequence one by one.
• 5. Heterogeneous (for some types): Some sequence types, like lists, can contain
elements of different types (e.g., integers, strings, objects), whereas others, like
strings, can only contain elements of a single type (characters).
• 6. Mutable or Immutable: - *Mutable*: Sequences like lists can be changed
after their creation, allowing elements to be added, removed, or modified. -
*Immutable*: Sequences like strings and tuples cannot be changed once created.
Any modification results in the creation of a new sequence.
• 7.Length: The length of a sequence (the number of elements) can be determined
using functions or methods (e.g., len() in Python).
• 8. Concatenation and Repetition: Sequences can often be concatenated (joined
together) or repeated using operators like + and * respectively.
• Here are examples of common sequence types in Python:-
• *String*: An immutable sequence of characters. Example: "hello"-
• *List*: A mutable sequence of elements, which can be of any type. Example: [1,
2, 3, "four"]-
• *Tuple*: An immutable sequence of elements, which can be of any type.
Example: (1, 2, 3, "four")
• These characteristics make sequence data types versatile and powerful tools for
handling collections of elements in programming.
1. STRINGS
• Strings in python are surrounded by either single quotation
marks, or double quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with the print () function:
• You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
• print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
• Assigning a string to a variable is done with the variable name followed by
an equal sign and the string:
• You can assign a multiline string to a variable by using three quotes:
• a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
• A string is considered to be a sequence type due to the following characteristics:
• 1. *Ordered Collection*: A string is an ordered collection of characters. Each character in the string has
a specific position, starting from index 0 up to the length of the string minus one.
• 2. *Indexable*: Individual characters in a string can be accessed using their indices. For example, in the
string "hello", h is at index 0, e is at index 1, and so on. python s = "hello" print(s[0]) # Output: h
print(s[1]) # Output: e
• 3. *Slicable*: Subsets of the string can be accessed using slicing, which allows for extracting parts of
the string by specifying a range of indices. python s = "hello" print(s[1:4]) #
• 4. *Iterable*: Strings can be iterated over, meaning you can loop through each character in the string.
python s = "hello" for char in s: print(char)
• 5. *Length*: The length of a string, which is the number of characters it contains, can be determined
using the len() function. python s = "hello" print(len(s)) # Output: 5
• 6. *Concatenation and Repetition*: Strings can be concatenated using the + operator and repeated
using the * operator. python s1 = "hello" s2 = "world" print(s1 + s2) # Output: helloworldOutput:
ell
• print(s1 * 3) # Output: hellohellohello
• 7. *Immutable*: Strings are immutable, meaning once a string is created, its characters cannot
be changed. Any operation that seems to modify a string will actually create a new string.
• python
• s = "hello" s = s.replace("h", "j") print(s) # Output: jello
• These features make strings behave like sequences, similar to lists and tuples, which is why
strings are classified as a sequence data type in programming.
• Slicing
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to return a
part of the string.
• Get the characters from position 2 to position 5
• b = "Hello, World!"
print(b[2:5])
• Get the characters from the start to position 5
• b = "Hello, World!"
print(b[:5])
• Get the characters from position 2, and all the way to the end:
• b = "Hello, World!"
print(b[2:])
• Get the characters:
• From: "o" in "World!" (position -5)
• To, but not included: "d" in "World!"
MODIFY STRINGS

• Python has a set of built-in methods that you can use on strings.
• The upper() method returns the string in upper case:
• A = "Hello, World!“
• print(a.upper())
• Lower Case
• The lower() method returns the string in lower case:
• a = "Hello, World!"
• print(a.lower())
REPLACE STRING

• The replace() method replaces a string with another string:


• a = "Hello, World!"
print(a.replace("H", "J"))
• The split() method returns a list where the text between the specified
separator becomes the list items.
• The split() method splits the string into substrings if it finds instances of
the separator
• a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!’]
LIST
• Lists are used to store multiple items in a single variable.
• Lists can contain data of different types. The things put away in the rundown are isolated
with a comma (,) and encased inside square sections [].
• To access the list's data, we can use slice [:] operators. Like how they worked with strings,
the list is handled by the concatenation operator (+) and the repetition operator (*).
• 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:
• Create a List:
• thislist = ["apple", "banana", "cherry"]
print(thislist)
• 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:
• Lists allow duplicate values:
• thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
• To determine how many items a list has, use the len() function:
• Print the number of items in the list:
• thislist = ["apple", "banana", "cherry"]
print(len(thislist))
• List items can be of any data type:
• 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))
• The list() Constructor
• It is also possible to use the list() constructor when creating a new list.
• Using the list() constructor to make a List:
• thislist = list(("apple", "banana", "cherry")) # note the double
round-brackets
print(thislist)
• 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:
• thislist = ["apple", "banana", "cherry"]
print(thislist[1])
• Note: The first item has index 0.
• 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])
• 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])
• returns the items from the beginning to, but NOT including, "kiwi":
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
• 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:])
• Range of Negative Indexes
• Specify negative indexes if you want to start the search from the end of the
list:
• 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])
• Check if Item Exists
• To determine if a specified item is present in a list use the in keyword:
• Example
• 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)
• thislist[1] = "blackcurrant"
print(thislist)
• 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)
• If you insert less items than you replace, the new items will be inserted
where you specified, and the remaining items will move accordingly:

• 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)
• Note: As a result of the example above, the list will now contain 4 items.
• Python - Add List Items
• 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)
• The elements will be added to the end of the list
• Add Any Iterable
• The extend() method does not have to append lists, you can add any iterable object
(tuples, sets, dictionaries etc.).
• Example
• Add elements of a tuple to a list:
• thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

PYTHON - REMOVE LIST ITEM
• The remove()method removes the specified item.
• Example
• Remove "banana":
• thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
• If there are more than one item with the specified value, the remove()

• The pop() method removes the specified index.


• Example
• Remove the second item:
• thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

• If you do not specify the index, the pop() method removes the last item.
• Example
• Remove the last item:
• thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
• The del keyword also removes the specified index:
• Example
• 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)
LAB QUESTION-2
• A) Create a list and perform the following methods 1) insert () 2) remove() 3)
append() 4)
• len() 5) pop() 6) clear().
PYTHON - LIST COMPREHENSION
• List Comprehension
• List comprehension offers a shorter syntax when you want to create a new list based on the values of an
existing list.
• Example:
• Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
• Without list comprehension you will have to write a for statement with a conditional test inside:
• Example
• fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
• With list comprehension you can do all that with only one line of code:
• fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
PYTHON - SORT LISTS
• Sort List Alphanumerically
• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
• Example:
• Sort the list alphabetically:
• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
• Example
• Sort the list numerically:
• thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
• Sort Descending
• To sort descending, use the keyword argument reverse = True
• Example
• Sort the list descending:
• thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
• Example
• Sort the list descending:
• thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)

• Sort the list descending:


• thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
COPY A LIST

• There are ways to make a copy, one way is to use the built-in List
method copy()
• Another way to make a copy is to use the built-in method list().
• Example
• Make a copy of a list with the list() method:
• thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
PYTHON - JOIN LISTS
• Join Two Lists
• There are several ways to join, or concatenate, two or more lists in Python.
• One of the easiest ways are by using the + operator.
• Example
• Join two list:
• list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
• Another way to join two lists is by appending all the items from list2 into list1, one by one:
• Example
• Append list2 into list1:
• list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)

• Or you can use the extend() method, where the purpose is to add
elements from one list to another list:
• Example
• Use the extend() method to add list2 at the end of list1:
• list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
• Python has a set of built-in methods that you can use on lists.
• mytuple = ("apple", "banana", "cherry")
PYTHON TUPLES
• 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.
• 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.

You might also like