Your ultimate guide

Datatypes in Python

Data Types
Understanding data types is a fundamental aspect of Python programming. Every value stored in a variable has a data type associated with it. In Python, you don't have to explicitly specify the data type, as it is assigned automatically based on the value you provide.

Python contains the following inbuilt data types:
Numeric Types: int, float, complex
Text Type: str
Sequence Types: list, tuple
Mapping Type: dict
Set Type: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray
None Type: None



Note:
  1. type(): This function is used to check the type of variable.
    • Syntax: type(variable)
  2. id(): This function gets the memory address of the object.
    • Syntax: id(variable)
  3. print(): The print function is used to display a specified message or variable values on the screen(console).



Numeric Types:
int datatype: An integer data type represents positive or negative whole numbers (without fraction or decimals numbers)
   Example:
        >>>a=60
        >>>type(a) #<class 'int'>

float datatype: it contains the decimal values.
    Example:
        >>>a = 10.5
        >>>type(a) #<class 'float'>

complex datatype: A complex number is in the form a+bj, where a and b contain integers or floating point values.
    Example:
        >>> a = 10+2.5j
        >>> b = 20+3.5j
        >>> c = a+b
        >>> print(c) #(30+6j)
        >>> type(c) #<class 'complex'>



Text Type:
String(str) datatype: Collection of characters (alphabets, numbers, symbols), it should be either in double quotes or single quotes.
    Example:
        >>> a = "Testing Colleges"
        >>> type(a)
        output: <class 'str'>

        >>> s = ''' Hello 'this' is "Testing" colleges '''
        >>> print(s)
        output: Hello 'this' is "Testing" colleges

        >>> s2 = "Python is 'object-oriented programming language"
        >>> print(s2)
        output: Python is an 'object-oriented programming language

        >>> s3 = 'Python is "easy" to learn
        >>> print(s3)
        output: Python is "easy" to learn

 Note: In many programming languages such as Java and C#, a single character within single quotes is treated as a char data type value. However, in Python, there is no char data type. Therefore, a single character within a single quote is treated as a string.
    Example:
        >>> ch = 'a'
         >>> type(ch)
         output: <class 'str'>

Slicing of String: 
  • The slice operator in Python is represented by the " [ ] " symbol, and it is used to retrieve parts of a string by index.
  • The index can be either positive or negative. 
  • When using a positive index, the slicing operation begins from the left side of the string, while a negative index starts the slicing operation from the right side of the string.

        

    Example:
        >>> s = "Testing Colleges"
        >>> s[0]     #'T'
        >>> s[1]     #'e'
        >>> s[-1]     #'s'

    Example 2:
        >>> s = "abcdefgh"
        >>> s[1:4]     #'bcd' (index: 1st to 4th)
        >>> s[:4]     #abcd (index: beginning to 4th)
        >>> s[:]     #abcdefgh (index: beginning to ending)
        >>> s[0:6:2]     #ace (index +2 : a(+2)c(+2)e)



Sequence Types:
 List datatype: 
  • list contains a collection of different data types.
    • Eg: newlist = [10, 30.2, "Hello"]
  • Whatever order values are given in the list same order will be preserved. (it doesn't change values into ascending or descending order)
  • Duplicate values are allowed.
    • Eg: newlist = [10, 10, 20, 30, 20]
  • We can change, add, and remove items in a list after it has been created.
  • The value should be enclosed within square brackets [ ].
(List is a collection of different datatypes, it should be defined under [ ], its Mutable, Ordered)
Example:
    >>> l = [10, 20.3, True, "hello", None]

    # Accessing element using index number
    >>> print(l[0]) 
    output: 10

    # print the last element in a list
    >>> print(l[-1]) 
    output: None

    >>> print(l[1:3]) 
    output: [20.3, True]

    # Changing the value in a list
    >>> l[0] = 15
    >>> print(l) 
    output: [15, 20.3, True, "hello", None]

    >>> l[5] = 20
    output: IndexError: list assignment index out of range

    # print the length of the list
    >>> print(len(l))
    output: 5
    
    # Adding variables in a list
    >>> l.append(20) 
    >>> print(l) 
    output: [15, 20.3, True, "hello", None, 20]

    # Removing variables in a list
    >>> l.remove("hello")
    >>> print(l) 
    output: [15, 20.3, True, None, 20]

    >>> g = [ ] #empty list
    >>> print(g) 
    output: []

tuple datatype:
  • tuple is exactly the same as the list except that it is immutable i.e. we cannot change values.
  • We can't increase or decrease the size of this tuple datatype. (immutable)
  • The value should be enclosed within parenthesis brackets ( )
(A tuple is a collection of different datatypes, it should be defined under ( ), it is immutable, Ordered)
Example:
    >>> t = (10, 20.5, 10, "hello")
    >>> t[0] 
    output: 10

    >>> t.append(30)
    AttributeError: 'tuple' object has no attribute 'append'
    >>> t.remove(10)
    AttributeError: 'tuple' object has no attribute 'remove'



Set Type:
Set datatype:
  • If we want to represent a group of values without duplicates where order is unimportant then we should go for set Datatype.
  • Insertion order is not preserved
  • Duplicates are not allowed
  • index concept is not applicable
  • We can increase or decrease the size of the set(mutable)
  • The value should be enclosed within curly brackets { }
(Set is a collection of different datatypes, it should be under { }, Mutable, Unordered)
    Example:
        >>> s = { 10, "testing", 20.5, 10 }
        >>> print(s) 
        output: { 10, "testing", 20.5 }

        >>> print(s[0])
            TypeError: 'set' object is not subscriptable

        # Adding variables in a set
        >>> s.add(5) 
        >>>print(s)
        output: { 5, 10, "testing", 20.5 }

        # Removing variables in a set
        >>> s.remove(10) 
        >>> print(s) #{ 5, "testing", 20.5 }

frozenset:
  • The frozen set is exactly the same as the set except that it is immutable ie., we cannot change the values.
    • Syntax:
    • forzenset([iterable])



Mapping Type:
Dictionary(dict) Datatype:
  • If we want to represent a group of values as key-value pairs then we should go for dict datatype.
  • The value should be enclosed within curly brackets { }, key and value separated by a colon :
    • Example: d = {1: 20, 2: "Testing", 3: True}
  • Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with the duplicate key then the old value will be replaced with the new value.
  • dict is mutable and the order won't be preserved.
    Example:
        >>> d = {1: 20, 2: "Testing", 3: True}
        >>> d[2] = 30
        >>> print(d) 
        output: {1: 20, 2: 30, 3: True}

        >>> d[5] = "hello"
        >>> print(d) 
        output: {1: 20, 2: 30, 3: True, 5: "hello"}



Boolean Type:
bool datatype: bool datatype only stores the values True and False. Internally Python represents True as 1 and False as 0.
    Example:
        >>> a = 10
        >>> b = 20
        >>> c = a>b
        >>> print(c) #False
        >>> type(c) #<class 'bool'>

        >>> True + True #2
        >>> True + Flase #1



Binary Types:
bytes:
    The 'bytes' data type in Python is used to work with binary data,
  • Using the 'bytes()' function you can create a 'bytes' object by giving it a list of numbers.
    • Example:
    • >>> b = bytes([10, 20, 30, 40])
    • >>> print(type(b))
    • output: <class 'bytes'>
  • Python bytes are a sequence of integers in the range of 0 - 255.
    • Example:
    • >>> l = [10, 20, 30, 256]
    • >>> b = bytes(l)
    • output: ValueError: bytes must be in range(0, 255)
  • The 'byte' data type is immutable, which means that once created, you cannot change its contents.
    • Example:
    • >>> l = [10, 20, 30, 40]
    • >>> b = bytes(l)
    • >>> print(b[0])
    • output: 10
    • >>> b[0] = 15
    • output: TypeError: 'bytes' object does not support item assignment.
bytearray:
  • The 'bytearray' is exactly the same as the 'bytes' except that it is mutable ie., we can change the values.
  • Using the 'bytearray()' function you can create a 'bytearray' object by giving it a list of numbers.
    • Example:
    • b = bytearray([10, 20, 30, 40])
    • print(type[b])
    • output: <class 'bytearray'>
    • print(b[0])
    • output: 10
    • print(b[-1])
    • output: 40
    • b[0] = 15
    • print(b[0])
    • output: 15



None Type:
None Datatype: None means Nothing or No value associated. If the value is unavailable, then none is introduced to handle such types of cases.
    Example:
        >>> a = None
        >>> type(a) #<class 'NoneType'>




Escape character in Python:
    An escape character in programming is a special character that is used to represent certain non-printable or reserved characters, as well as to enable the use of characters that might otherwise be interpreted differently. Escape characters are typically denoted by a backslash ('\') followed by a specific character.
  • \n  ->  Which is used to start a new line in text.
    • Example:
    • print("Python is an \n interpreted language")
    • output:
      • Python is an
      • interpreted language
  • \t  ->  Which is used for creating horizontal spacing.
    • Example:
    • print("Python is an \t interpreted language")
    • output: Python is an      interpreted language
  • \r  ->  Carriage Return Character, often used in text files for moving the cursor to the beginning of a line.
  • \b  ->  BackSpace Character, which is used to move the cursor back one space.
  • \f  ->  Form Feed Character, used in some text files and printing systems to indicate a page break or advance to the next page. In most cases, it doesn't have a visible effect when displayed in a terminal or text editor.
  • \v  ->  Vertical Tab Character, Used for vertical spacing in text, but it is rarely used in modern programming and text formatting. Like the form feed character, it doesn't have a visible effect in most text editors or terminals.
  • \'  ->  Singel quote
    • Example:
    • print("Python is an \'interpreted\' language")
    • output: Python is an 'interpreted' language
  • \"  ->  Double quote
    • Example:
    • print("Python is an \"interpreted\" language")
    • output: Python is an "interpreted" language
  • \\  ->  back slash symbol
    • Example:
    • print("Hello\\world!")
    • output: Hello\world!





Python provides a variety of built-in functions for working with lists. Here are some of the most commonly used ones:

1. `len(list)`: Returns the number of elements in the list.
2. `append(item)`: Adds an item to the end of the list.
3. `extend(iterable)`: Appends the elements of an iterable (e.g., another list) to the end of the list.
4. `insert(index, item)`: Inserts an item at a specific index.
5. `remove(item)`: Removes the first occurrence of a specific item.
6. `pop(index)`: Removes and returns the item at a specific index. If no index is provided, it removes and returns the last item.
7. `index(item)`: Returns the index of the first occurrence of the specified item.
8. `count(item)`: Returns the number of times a specific item appears in the list.
9. `sort()`: Sorts the list in ascending order.
10. `sort(reverse=True)`: Sorts the list in descending order.
11. `reverse()`: Reverses the order of elements in the list.
12. `copy()`: Returns a shallow copy of the list.
13. `clear()`: Removes all items from the list.
14. `min(list)`: Returns the minimum value in the list.
15. `max(list)`: Returns the maximum value in the list.
16. `sum(list)`: Returns the sum of all elements in the list.
17. `sorted(iterable)`: Returns a new sorted list from the elements of an iterable without modifying the original list.
18. `any(iterable)`: Returns `True` if any element in the iterable is `True`.
19. `all(iterable)`: Returns `True` if all elements in the iterable are `True`.
20. `zip(iterable1, iterable2)`: Combines two or more iterables into tuples, stopping when the shortest iterable is exhausted.
21. `enumerate(iterable)`: Returns an iterator that yields pairs of index and value for each element in the iterable.
22. `filter(function, iterable)`: Returns an iterator containing only the elements of the iterable for which the function returns `True`.

These are some of the most commonly used list-related functions in Python. Depending on your specific use case, you may find other functions or methods from the Python standard library that can be useful for working with lists.



Tuples are similar to lists in Python, but they are immutable, meaning their elements cannot be modified after creation. While there are fewer built-in functions and methods specifically tailored for tuples compared to lists, you can use some functions that are common to both data types. Here are the commonly used functions and methods when working with tuples in Python:

1. `len(tuple)`: Returns the number of elements in the tuple.
2. `count(item)`: Returns the number of times a specific item appears in the tuple.
3. `index(item)`: Returns the index of the first occurrence of the specified item.
4. `sorted(iterable)`: Returns a new sorted list from the elements of an iterable without modifying the original tuple.
5. `min(tuple)`: Returns the minimum value in the tuple.
6. `max(tuple)`: Returns the maximum value in the tuple.
7. `sum(tuple)`: Returns the sum of all elements in the tuple.
8. `any(iterable)`: Returns `True` if any element in the iterable is `True`.
9. `all(iterable)`: Returns `True` if all elements in the iterable are `True.
10. `zip(iterable1, iterable2)`: Combines two or more iterables into tuples, stopping when the shortest iterable is exhausted.
11. `enumerate(iterable)`: Returns an iterator that yields pairs of index and value for each element in the iterable.
12. `filter(function, iterable)`: Returns an iterator containing only the elements of the iterable for which the function returns `True`.

Remember that since tuples are immutable, functions like `append`, `extend`, `insert`, and `sort` that modify the contents of a data structure are not applicable to tuples. Tuples are typically used when you want to create a collection of items that should not be changed after creation, while lists are used for collections that may need to be modified.

These functions and methods should cover most of your needs when working with tuples in Python.



In Python, you can work with both sets and frozensets. Sets are mutable, while frozensets are immutable. Here are the built-in functions and methods for working with sets and frozensets:

### For Sets (Mutable):
1. `set(iterable)`: Creates a new set from an iterable.
2. `add(element)`: Adds an element to the set.
3. `update(iterable)`: Updates the set by adding elements from an iterable.
4. `remove(element)`: Removes an element from the set. Raises an error if the element is not present.
5. `discard(element)`: Removes an element from the set if it exists; does not raise an error if the element is not present.
6. `pop()`: Removes and returns an arbitrary element from the set. Raises an error if the set is empty.
7. `clear()`: Removes all elements from the set.
8. `copy()`: Returns a shallow copy of the set.
9. `difference(other)`: Returns a new set containing elements that are in the current set but not in the other set.
10. `difference_update(other)`: Updates the set by removing elements that are also in the other set.
11. `intersection(other)`: Returns a new set containing elements that are in both the current set and the other set.
12. `intersection_update(other)`: Updates the set by keeping only elements that are also in the other set.
13. `union(other)`: Returns a new set containing all unique elements from both the current set and the other set.
14. `update(other)`: Updates the set by adding elements from another set.
15. `issubset(other)`: Returns `True` if the set is a subset of the other set.
16. `issuperset(other)`: Returns `True` if the set is a superset of the other set.
17. `isdisjoint(other)`: Returns `True` if the set has no elements in common with the other set.

### For Frozensets (Immutable):
1. `frozenset(iterable)`: Creates a new frozenset from an iterable.
2. `copy()`: Returns a shallow copy of the frozenset.
3. `difference(other)`: Returns a new frozenset containing elements that are in the current frozenset but not in the other frozenset.
4. `intersection(other)`: Returns a new frozenset containing elements that are in both the current frozenset and the other frozenset.
5. `union(other)`: Returns a new frozenset containing all unique elements from both the current frozenset and the other frozenset.
6. `issubset(other)`: Returns `True` if the frozenset is a subset of the other frozenset.
7. `issuperset(other)`: Returns `True` if the frozenset is a superset of the other frozenset.
8. `isdisjoint(other)`: Returns `True` if the frozenset has no elements in common with the other frozenset.

Frozensets do not have methods for adding or removing elements since they are immutable. They are often used as keys in dictionaries or elements of other sets due to their immutability.

These functions and methods should cover most of your needs when working with sets and frozensets in Python.




Python dictionaries (dicts) are a versatile and widely used data structure. Here are the built-in functions and methods for working with dictionaries:

### Creating Dictionaries:
1. `dict()`: Creates an empty dictionary.
2. `dict(key=value, ...)`: Creates a dictionary with key-value pairs.
3. `dict(iterable)`: Creates a dictionary from an iterable of key-value pairs (e.g., a list of tuples).

### Accessing and Modifying Elements:
4. `d[key]`: Accesses the value associated with a specific key. Raises a `KeyError` if the key is not present.
5. `d.get(key)`: Accesses the value associated with a key. Returns `None` if the key is not present (no error).
6. `d.get(key, default)`: Accesses the value associated with a key, returning the specified default value if the key is not present.
7. `d.keys()`: Returns a view of all keys in the dictionary.
8. `d.values()`: Returns a view of all values in the dictionary.
9. `d.items()`: Returns a view of key-value pairs in the dictionary.
10. `d.pop(key)`: Removes and returns the value associated with a specific key. Raises a `KeyError` if the key is not present.
11. `d.pop(key, default)`: Removes and returns the value associated with a key, returning the specified default value if the key is not present.
12. `d.popitem()`: Removes and returns an arbitrary key-value pair as a tuple.
13. `d.update(other_dict)`: Updates the dictionary with key-value pairs from another dictionary.
14. `d.setdefault(key, default)`: Returns the value associated with a key, or sets it to the default value if the key is not present.

### Dictionary Views:
15. `dict.keys()`: Returns a view of keys in the dictionary.
16. `dict.values()`: Returns a view of values in the dictionary.
17. `dict.items()`: Returns a view of key-value pairs in the dictionary.

### Dictionary Methods:
18. `d.clear()`: Removes all key-value pairs from the dictionary.
19. `d.copy()`: Returns a shallow copy of the dictionary.
20. `d.fromkeys(iterable, value)`: Creates a new dictionary with keys from an iterable and values set to a specified value.
21. `d.setdefault(key, default)`: Returns the value associated with a key, or sets it to the default value if the key is not present.
22. `d.update(other_dict)`: Updates the dictionary with key-value pairs from another dictionary.

### Other Functions:
23. `len(d)`: Returns the number of key-value pairs in the dictionary.
24. `sorted(d)`: Returns a sorted list of keys in the dictionary.
25. `in` and `not in` operators: Check if a key exists in the dictionary.

These are the primary functions and methods used when working with dictionaries in Python. Dictionaries are a fundamental data structure for storing key-value pairs and are commonly used in a wide range of applications.

No comments:

Post a Comment