Data Types
It’s time to look at different data types we may find useful in our course. Besides the number types mentioned previously, there are also other types like strings, lists, tuples, dictionaries and sets.
| Data Types | Classes | Description |
|---|---|---|
| Numeric | int, float, complex | Holds numeric values |
| String | str | Stores sequence of characters |
| Sequence | list, tuple, range | Stores ordered collection of items |
| Mapping | dict | Stores data as key-value pairs |
| Boolean | bool | Holds either True or False |
| Set | set, frozenset | Holds collection of unique items |
Each of these data types has a number of connected methods (functions) which allow you to manipulate the data contained in a variable. If you want to know which methods are available for a certain object use the command dir, e.g.
s = "string"
dir(s)
The output would be:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix',
'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
The following few cells will give you a short introduction into each type.
Data Types
Python supports several numeric data types including integers, floats, and complex numbers.
You can perform various arithmetic operations with numeric types:
Type conversion works between numeric types:
Strings are lists of keyboard characters as well as other characters not on your keyboard. They are useful for printing results on the screen, during reading and writing of data.
String can be concatenated using the + operator.
As strings are lists, each character in a string can be accessed by addressing the position in the string (see Lists section)
Strings can also be made out of numbers.
If you want to obtain a number of a string, you can use what is known as type casting. Using type casting you may convert the string or any other data type into a different type if this is possible. To find out if a string is a pure number you may use the str.isnumeric method. For the above string, we may want to do a conversion to the type int by typing:
There are a number of methods connected to the string data type. Usually the relate to formatting or finding sub-strings. Formatting will be a topic in our next lecture. Here we just refer to one simple find example.
Lists are ordered, mutable collections that can store items of different data types.
You can access and modify list elements:
Common list methods:
Tuples are ordered, immutable sequences.
Tuples are immutable, meaning you cannot change their elements after creation:
Dictionaries store data as key-value pairs. They are mutable and unordered.
Accessing and modifying dictionary elements:
Common dictionary methods:
The Boolean type has only two possible values: True and False.
Boolean values are commonly used in conditional statements:
Boolean operations:
Sets are unordered collections of unique elements.
Common set operations:
Adding and removing elements:
Type Casting
Type casting is the process of converting a value from one data type to another. Python provides built-in functions for type conversion.
Python offers several built-in functions for type conversion: - int(): Converts to integer - float(): Converts to float - str(): Converts to string - bool(): Converts to boolean - list(): Converts to list - tuple(): Converts to tuple - set(): Converts to set - dict(): Converts from mappings or iterables of key-value pairs
Let’s explore various type conversion examples with practical code demonstrations. These examples show how Python handles conversions between different data types.
Numeric Conversions
When converting between numeric types, it’s important to understand how precision and data may change. For example, converting floats to integers removes the decimal portion without rounding.
String Conversions
String conversions are commonly used when processing user input or preparing data for output. Python provides straightforward functions for converting between strings and numeric types.
Collection Type Conversions
Python allows for easy conversion between different collection types, which is useful for changing the properties of your data structure (like making elements unique with sets).
Boolean Conversion
Boolean conversion is essential for conditional logic. Python follows specific rules to determine truthiness of values, with certain “empty” or “zero” values converting to False.
When converting to boolean with bool(), the following values are considered False: - 0 (integer) - 0.0 (float) - "" (empty string) - [] (empty list) - () (empty tuple) - {} (empty dictionary) - set() (empty set) - None
Everything else converts to True.
Special Cases and Errors
Type conversion can sometimes fail, especially when the source value cannot be logically converted to the target type. Understanding these limitations helps prevent runtime errors in your code.
Not all type conversions are possible. Python will raise an error when the conversion is not possible.
To handle potential errors in type conversion, you can use exception handling with try/except blocks: