Python Native Data Types

PYTHON NUMBERS

  • Number data types store numeric values. They are immutable data types, which means that changing the value of a number data type results in a newly allocated object.
  • Number objects are created when you assign a value to them.
  • For example

  • You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −

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

  • There are three numeric types in Python:
    • int
    • float
    • complex
  • Variables of numeric types are created when you assign a value to them:

  • To verify the type of any object in Python, use the type() function:
  • Example:

NUMBER TYPE CONVERSION

  • Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.
    • Type int(x) to convert x to a plain integer.
    • Type long(x) to convert x to a long integer.
    • Type float(x) to convert x to a floating-point number.
    • Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
    • Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions

INT

  • int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
  • Example:

FLOAT

  • Float, or "floating-point number" is a number, positive or negative, containing one or more decimals.
  • Example:

  • Float can also be scientific numbers with an "e" to indicate the power of 10.
  • Example:

COMPLEX

  • Complex numbers are written with a "j" as the imaginary part:
  • Example:

TYPE CONVERSION

  • You can convert from one type to another with the int(), float(), and complex() methods:
  • Example: Convert from one type to another

  • Note: You cannot convert complex numbers into another number type.

PYTHON LISTS

  • A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can modify its element after it is created. However, Python consists of six data types that are capable to store the sequences, but the most common and reliable type is the list.
  • A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets [].
  • A list can be defined as below

  • To access values in lists, use the square brackets for slicing along with the index or indices to obtain the value available at that index.
  • For example −

  • When the above code is executed, it produces the following result

BASIC LIST OPERATIONS

  • Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
  • In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.

  • Indexing, Slicing, and Matrixes
  • Because lists are sequences, indexing, and slicing work the same way for lists as they do for strings.
  • Assuming following input −


  • We can get the sub-list of the list using the following syntax.

  • The start denotes the starting index position of the list.
  • The stop denotes the last index position of the list.
  • The step is used to skip the nth element within a start: stop
  • Consider the following example:

  • Output

  • Unlike other languages, Python provides the flexibility to use negative indexing also. The negative indices are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent left element is present at the index -2 and so on until the left-most elements are encountered.

  • Let's have a look at the following example where we will use negative indexing to access the elements of the list.

  • Output:

BUILT-IN LIST FUNCTIONS & METHODS

  • Python includes the following list functions −

  • Example
  • Create a List:

  • ACCESS ITEMS
    • Example: Print the second item of the list

  • NEGATIVE INDEXING
    • Negative indexing means beginning 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

  • 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: Print the second item of the list

    • Example: This example returns the items from the beginning to "orange":

    • 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" and to the end:

  • 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 index -4 (included) to index -1 (excluded)

  • CHANGE ITEM VALUE
    • To change the value of a specific item, refer to the index number:
    • Example: Change the second item

  • LOOP THROUGH A LIST
    • You can loop through the list items by using a for loop:
    • Example: Print all items in the list, one by one

  • CHECK IF ITEM EXISTS
    • To determine if a specified item is present in a list use the in a keyword:
    • Example: Check if "apple" is present in the list

  • LIST LENGTH
    • To determine how many items a list has, use the len() function:
    • Example: Print the number of items in the list

  • ADD ITEMS
    • To add an item to the end of the list, use the append() method:
    • Example: Using the append() method to append an item

    • To add an item at the specified index, use the insert() method:
    • Example: Insert an item as the second position

  • REMOVE ITEM
    • There are several methods to remove items from a list:
    • Example: The remove() method removes the specified item:

    • Example: The pop() method removes the specified index, (or the last item if index is not specified):

    • Example: The del keyword removes the specified index:

    • Example: The del keyword can also delete the list completely

    • Example: The clear() method empties the list

  • COPY A LIST
    • You cannot copy a list simply by typing list2 = list1, because list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
    • There are ways to make a copy, one way is to use the built-in List method copy().
    • Example: Make a copy of a list with the copy() method

    • 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

  • JOIN TWO LISTS
    • There are several ways to join or concatenate, two or more lists in Python.
    • One of the easiest ways is by using the + operator.
    • Example: Join two list

    • Another way to join two lists are by appending all the items from list2 into list1, one by one
    • Example: Append list2 into list1

    • Or you can use the extend() method, which purpose is to add elements from one list to another list
    • Example: Use the extend() method to add list2 at the end of list1

  • THE list() CONSTRUCTOR
    • It is also possible to use the list() constructor to make a new list.
    • Example: Using the list() constructor to make a List

PYTHON TUPLES

  • Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the value of the items stored in the list can be changed, whereas the tuple is immutable, and the value of the items stored in the tuple cannot be changed and tuples use parentheses, whereas lists use square brackets.

  • CREATING A TUPLE
    • A tuple can be written as the collection of comma-separated (,) values enclosed with the small () brackets. The parentheses are optional but it is good practice to use. A tuple can be defined as follows.

    • The empty tuple is written as two parentheses containing nothing −

    • To write a tuple containing a single value you have to include a comma, even though there is only one value −

    • tuple indices start at 0, and they can be sliced, concatenated, and so on.

  • ACCESSING VALUES IN TUPLES
    • To access values in a tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index.
    • For example −

    • When the above code is executed, it produces the following result −

    • Example

    • Output:

    • Example

    • Output:

    • Example: Create a Tuple

  • 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

  • NEGATIVE INDEXING
    • Negative indexing means beginning 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

  • 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

    • Note: The search will start at index 2 (included) and end at index 5 (not included). Remember that the first item has an index 0.

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

    • Example

    • Output:

    • In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an element outside of tuple that raised an IndexError.

  • 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

  • LOOP THROUGH A TUPLE
    • You can loop through the tuple items by using a for a loop.
    • Example: Iterate through the items and print the values

  • CHECK IF ITEM EXISTS
    • To determine if a specified item is present in a tuple using the in a keyword:
    • Example: Check if "apple" is present in the tuple

  • ADD ITEMS
    • Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
    • Example: - You cannot add items to a tuple:

  • 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 comma

  • REMOVE ITEMS
    • Note: You cannot remove items in a tuple.
    • Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
    • Example: The del keyword can delete the tuple completely

  • JOIN TWO TUPLES
    • To join two or more tuples you can use the + operator:
    • Example: Join two tuples

  • THE tuple() CONSTRUCTOR
    • It is also possible to use the tuple() constructor to make a tuple.
    • Example: Using the tuple() method to make a tuple

  • TUPLE METHODS
    • Python has two built-in methods that you can use on tuples.

  • BASIC TUPLES OPERATIONS
    • Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
    • In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −

  • INDEXING, SLICING, AND MATRIXES
    • The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from 0 and goes to length(tuple) - 1.
    • The items in the tuple can be accessed by using the index [] operator. Python also allows us to use the colon operator to access multiple items in the tuple.
    • Consider the following image to understand the indexing and slicing in detail.

    • Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −

    • Example

    • Output:

    • In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an element outside of tuple that raised an IndexError.
    • Example

    • Output:

  • BASIC TUPLE OPERATIONS
    • The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they work with the list. Consider the following table for more detail.
    • Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

  • BUILT-IN TUPLE FUNCTIONS
    • Python includes the following tuple functions −

  • WHERE USE TUPLE?
    • Using tuple instead of a list is used in the following scenario.
    • Using tuple instead of the list gives us a clear idea that tuple data is constant and must not be changed.
    • Tuple can simulate a dictionary without keys. Consider the following nested structure, which can be used like a dictionary.

  • List vs. Tuple

PYTHON SETS

  • A Python set is the collection of unordered items. Each element in the set must be unique, immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify them after their creation.
  • Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together, or we can get the list of elements by looping through the set.

  • CREATING A SET

    • The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also provides the set() method, which can be used to create the set by the passed sequence.
    • A set is a collection that is unordered and unindexed. In Python, sets are written with curly brackets.
    • Example: Create a Set

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

    • Output:

    • Example

    • Output

  • ACCESS ITEMS
    • You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
    • 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 the keyword.
    • Example: Loop through the set, and print the values

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

  • CHANGE ITEMS
    • Once a set is created, you cannot change its items, but you can add new items.
  • ADD ITEMS
    • To add one item to a set use the add() method.
    • To add more than one item to a set use the update() method.
    • Example: Add an item to a set, using the add() method

    • Example: Add multiple items to a set, using the update() method

  • 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

  • REMOVE ITEM
    • To remove an item in a set, use the remove(), or the discard() method.
    • Example: Remove "banana" by using the remove() method

    • Note: If the item to remove does not exist, remove() will raise an error.
    • Example: Remove "banana" by using the discard() method

    • Note: If the item to remove does not exist, discard() will NOT raise an error.
    • You can also use the pop(), a 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

    • Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
    • Example: The clear() method empties the set

    • Example: The del keyword will delete the set completely

  • JOIN TWO SETS
    • There are several ways to join two or more sets in Python.
    • You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:
    • Example: The union() method returns a new set with all items from both sets

    • Example: The update() method inserts the items in set2 into set1

    • Note: Both union() and update() will exclude any duplicate items.
    • There are other methods that join two sets and keep ONLY the duplicates, or NEVER the duplicates.
  • THE set() CONSTRUCTOR
    • It is also possible to use the set() constructor to make a set.
    • Example: Using the set() constructor to make a set

  • SET METHODS
    • Python has a set of built-in methods that you can use on sets.

PYTHON DICTIONARY

  • Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. It is a mutable data structure. The dictionary is defined into element Keys and values.
    • Keys must be a single element
    • Value can be any type such as list, tuple, integer, etc.
  • In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.

  • Creating the dictionary

    • The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and each key is separated from its value by the colon (:).
    • The syntax to define the dictionary is given below.

    • In the above dictionary Dict, The keys Name, and Age are the string that is immutable object.
    • Example: Create and print a dictionary

    • Output:

    • Example: Create and print a dictionary

    • Output:

  • Python provides the built-in function dict() method which is also used to create dictionary. The empty curly braces {} is used to create empty dictionary.

  • Output:

  • Accessing the dictionary values
    • We have discussed how the data can be accessed in the list and tuple by using indexing.
    • However, the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary.
    • Example: The dictionary values can be accessed in the following way

    • Output:

    • Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing.
    • Example: The dictionary values can be accessed in the following way

    • Output:

    • There is also a method called get() that will give you the same result:
    • Example: Get the value of the "model" key

    • Output:

    • If we attempt to access a data item with a key, which is not part of the dictionary, we get an error
    • Example:

    • Output:

  • Adding dictionary values
    • The dictionary is a mutable data type, and its values can be updated by using the specific keys. The value can be updated along with key Dict[key] = value. The update() method is also used to update an existing value.
    • Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the dictionary.
    • Let's see an example to update the dictionary values.

    • Output:

  • Loop Through a Dictionary
    • You can loop through a dictionary by using a for loop.
    • When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
    • Example: - Print all key names in the dictionary, one by one:

    • Example: - Print all key names in the dictionary, one by one

    • Output:

    • Example: - Print all values in the dictionary, one by one:

    • Output:

    • Example: - You can also use the values() method to return values of a dictionary:

    • Output:

    • Example: - Loop through both keys and values, by using the items() method:

    • Output:

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

    • Output:

  • Dictionary Length
    • To determine how many items (key-value pairs) a dictionary has, use the len() function.
    • Example: - Print the number of items in the dictionary:

    • Output:

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

    • Output:

  • Removing Items
    • There are several methods to remove items from a dictionary:
    • Example: - The pop() method removes the item with the specified key name:

    • Output:

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

    • Output:

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

    • Output:

    • Example: - The del keyword can also delete the dictionary completely:

    • Output:

    • Example: - The clear() method empties the dictionary:

    • Output:

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

    • Output:

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

    • Output:

  • Nested Dictionaries
    • A dictionary can also contain many dictionaries, this is called nested dictionaries.
    • Example: - Create a dictionary that contains three dictionaries:

    • Output:

    • Or, if you want to nest three dictionaries that already exists as dictionaries:
    • Example: - Create three dictionaries, then create one dictionary that will contain the other three dictionaries:

    • Output:

  • The dict() Constructor
    • It is also possible to use the dict() constructor to make a new dictionary:
    • Example

    • Output:

  • Built-in Dictionary functions
    • The built-in python dictionary methods along with the description are given below.

  • Built-in Dictionary methods
    • The built-in python dictionary methods along with the description are given below.

PYTHON STRINGS

  • Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes.
  • The computer does not understand the characters; internally, it stores manipulated characters as the combination of the 0's and 1's.
  • Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the collection of Unicode characters.
  • Consider the following example in Python to create a string.
  • Syntax:
  • Here, if we check the type of the variable str using a Python script 
  • In Python, strings are treated as the sequence of characters, which means that Python doesn't support the character data type; instead, a single character written as 'p' is treated as the string of length 1.

  • Creating String in Python

    • We can create a string by enclosing the characters in single- quotes or double quotes.
    • Python also provides triple-quotes to represent the string, but it is generally used for multiline strings or docstrings.
    • 'hello' is the same as "hello".
    • You can display a string literal with the print() function:
    • Example:
    • Output:
  • Strings indexing and splitting
    • Like other languages, the indexing of the Python strings starts from 0.
    • For example, The string "HELLO" is indexed as given in the below figure.
    • Consider the following example:
    • Output:
    • As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use the : (colon) operator in Python to access the substring from the given string. Consider the following example.
    • Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
    • Consider the following example:
    • Output:
    • We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The second rightmost index indicates -2, and so on. Consider the following image.
    • Consider the following example
    • Output:

  • Reassigning Strings

    • Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.
    • Consider the following example.
    • However, in this example 1, the string str can be assigned completely to new content as specified in the following example.
    • Example

  • Deleting the String

    • As we know that strings are immutable. We cannot delete or remove the characters from the string.
    • But we can delete the entire string using the del keyword.
    • Output
    • Now we are deleting the entire string.
    • Output:

  • String Operators

    • Consider the following example to understand the real use of Python operators.
    • Output:

Python String Formatting

  • Escape Sequence
    • Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can be written in single quotes or double quotes but it will raise the SyntaxError as it contains both single and double-quotes.
    • Example
    • Consider the following example to understand the real use of Python operators.
    • Output:
    • We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
    • The backslash(/) symbol denotes the escape sequence.
    • The backslash can be followed by a special character and it is interpreted differently.
    • The single quotes inside the string must be escaped.
    • We can apply the same as in the double-quotes.
    • Example
    • Output:
  • The list of an escape sequences is given below:
    • Here is a simple example of an escape sequence.
    • Output:
    • We can ignore the escape sequence from the given string by using the raw string. We can do this by writing r or R in front of the string. Consider the following example.
    • Output:

  • The format() method
    • The format() method is the most flexible and useful method in formatting strings.
    • The curly braces {} are used as the placeholder in the string and replaced by the format() method argument.
    • Let's have a look at the given example:
    • Output:
  • Python String Formatting Using % Operator
    • Python allows us to use the format specifiers used in C's printf statement.
    • The format specifiers in Python are treated in the same way as they are treated in C.
    • However, Python provides an additional operator %, which is used as an interface between the format specifiers and their values.
    • In other words, we can say that it binds the format specifiers to the values.
    • Consider the following example.
    • Output:
  • String Length
    • To get the length of a string, use the len() function.
    • Example
    • The len() function returns the length of a string:
    • Output:
  • String Methods
    • Python has a set of built-in methods that you can use on strings.
    • Example
    • The strip() method removes any whitespace from the beginning or the end:
    • Output:
    • Example
    • The lower() method returns the string in lower case:
    • Output:
    • Example
    • The upper() method returns the string in the upper case:
    • Output:
    • Example
    • The replace() method replaces a string with another string:
    • Output:
    • Example
    • The split() method splits the string into substrings if it finds instances of the separator:
    • Output:
  • Check String
    • To check if a certain phrase or character is present in a string, we can use the keywords in or not in.
    • Example
    • Check if the phrase "ain" is present in the following text:
    • Output:
    • Example
    • Check if the phrase "ain" is NOT present in the following text:
    • Output:
  • String Concatenation
    • To concatenate, or combine, two strings you can use the + operator.
    • Example
    • Merge variable a with variable b into variable c:
    • Output:
    • Example
    • To add a space between them, add a " ":
    • Output:
  • String Format
    • As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:
    • Example
    • Output:
    • But we can combine strings and numbers by using the format() method!
    • The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:
    • Example
    • Use the format() method to insert numbers into strings:
    • Output:
    • The format() method takes an unlimited number of arguments, and are placed into the respective placeholders:
    • Example
    • Output:
    • You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
    • Example
    • Output:
  • Python String functions
    • Python provides various in-built functions that are used for string handling. Many String fun

Comments

Popular posts from this blog

Modules

Control Structures

Classes and Objects