Datatypes
Datatypes
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
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
• 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()
• 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
• 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.
•