This article entitle Python Datatype is a continuation of the previous article entitled Python Variables.
Datatype in Python is used to specify a type of variable and also specify what kind of data was going to store in the given variable.
What is Python Datatype?
In Python, datatypes are a categorization or a classification of data items and also represent a kind of value that tells what kind of operations will be performed on the particular data.
Further, since Python is Object-oriented programming it means that data types are actually classes and those variables are instance objects of the classes.
Basic data types in Python
- Numeric – int, float, complex
- String – str
- Sequence – list, tuple, range
- Binary – bytes, bytearray, memoryview
- Mapping – dict
- Boolean – bool
- Set – set, frozenset
- None – NoneType
Numeric Data Type
The numeric data type is used to store numeric values and number objects are created when assigning a value to them.
Example
num1 = 2 num2 = 20 num3 = 20.013
Python also supports 4 different types of numerical
- int (signed integers)
- long (long integers, they can be represented by octal and hexadecimal)
- float (floating point real values)
- complex (complex numbers)
Examples
int | float | long | complex |
20 | 0.0 | 61826362L | 5.34j |
200 | 34.20 | -0x16343L | 76.j |
-876 | -35.4 | 01342L | 8.762e-98j |
090 | 42.6+e189 | 0xDEFABCECBDAECBFBAEl | .765j |
-0580 | -80. | 7656873629843L | -.6754+0J |
-0x350 | -52.74e300 | -06753838172735L | 4e+16J |
-0x79 | 50.5-E15 | -4628264529L | 6.76e-7j |
TAKE NOTE:
Python also allows to use the lowercase ( l ) with a long, but to avoid confusion it is always recommended to use the uppercase L.
The complex number consists of ordered pair with a real floating number which has been denoted by an x + yj, where the x and y are the real numbers and the j is a unit imaginary.
Example
# integer variable. a=250 print("The type of variable having value", a, " is ", type(a)) # float variable. b=30.555 print("The type of variable having value", b, " is ", type(b)) # complex variable. c=20+3j print("The type of variable having value", c, " is ", type(c))
Output
The type of variable having value 250 is <class 'int'> The type of variable having value 30.555 is <class 'float'> The type of variable having value (20+3j) is <class 'complex'>
String Data Type in Python
The string data type is identified as a contiguous set of characters that have been represented by quotation marks and also allows for either a pair of single or double quotes.
The subset of a string can be taken by the use of the slice operator ([ ] and [:] ) with an index that starts at 0 at the beginning of a string to proceed way from -1 at the end.
Further, a plus ( – ) sign is the concatenation string operator and the asterisk ( * ) is a reputation operator.
Example
str = 'Hello Sourcecodehero!' print (str) # Prints complete string print (str[0]) # Prints first character of the string print (str[2:5]) # Prints characters starting from 3rd to 5th print (str[2:]) # Prints string starting from 3rd character print (str * 2) # Prints string two times print (str + "TEST") # Prints concatenated string
Output
Hello Sourcecodehero! H llo llo Sourcecodehero! Hello Sourcecodehero!Hello Sourcecodehero! Hello Sourcecodehero!TEST
List Data Type in Python
Lists data type contains an item that has been separated by a comma and enclosed with square brackets ( [] ) and it is the most versatile compound data type.
Further, lists are very similar to arrays in the C programming language. The only difference between them is all the items that belong to a Python list can have different positive and negative built-in data types. While in C array can only store elements that have been related to a particular data type.
The values that have been stored in a list can get by using the slice operator ( [ ] and [:] ) and the indexes will always start at 0 at the beginning of the list and ends with a -1.
Lastly, plus ( + ) sign is the concatenation operator for the list, and the asterisk ( * ) symbol is the repetition operator.
Example
list = [ 'Glenn', 893 , 4.34, 'jude', 26.1 ] tinylist = [342, 'jude'] print (list) # Prints complete list print (list[0]) # Prints first element of the list print (list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting from 3rd element print (tinylist * 2) # Prints list two times print (list + tinylist) # Prints concatenated lists
Output
['Glenn', 893, 4.34, 'jude', 26.1] Glenn [893, 4.34] [4.34, 'jude', 26.1] [342, 'jude', 342, 'jude'] ['Glenn', 893, 4.34, 'jude', 26.1, 342, 'jude']
Tuple Data Type in Python
Tuples are an immutable sequence data type that is similar to a list and also consists of a number of values that are separated by commas. But tuples are enclosed with parenthesis within.
The differences between tuples and lists:
- Tuples were enclosed with a parenthesis ( () ) and cannot be updated.
- The list was enclosed by brackets ( [] ) and the size and elements are changeable.
Example
tuple = ( 'Glenn', 893 , 4.34, 'jude', 26.1 ) tinytuple = (342, 'jude') print (tuple) # Prints the complete tuple print (tuple[0]) # Prints first element of the tuple print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd print (tuple[2:]) # Prints elements of the tuple starting from 3rd element print (tinytuple * 2) # Prints the contents of the tuple twice print (tuple + tinytuple) # Prints concatenated tuples
Output
('Glenn', 893, 4.34, 'jude', 26.1) Glenn (893, 4.34) (4.34, 'jude', 26.1) (342, 'jude', 342, 'jude') ('Glenn', 893, 4.34, 'jude', 26.1, 342, 'jude')
Ranges in Python
range() is a built-in function that returns a sequence of numbers that start from 0 and increments to 1 until it was reach a specified given number.
The range() function uses a for and a while loop in order to generate a sequence of Python numeric data types.
Syntax
range(start, stop, step)
The following list is the description of the parameters used.
- Start – an integer number that specifies the starting position, (Optional, Default: 0).
- Stop – an integer number that specifies the starting position, (Mandatory).
- Step – an integer number that specifies increment (Optional, Default: 1).
Example
for i in range(5): print(i)
Output
0 1 2 3 4
Dictionary in Python
Python dictionary is a kind of hash table that works similarly to associative arrays or hashes that can be found in Perl and it consists of key-value pairs.
Further, a dictionary key is almost any type in Python and usually, it was a string or number. Dictionaries are enclosed within by curly braces ( {} ) and the values can be accessed and assigned with the use of square braces ( [] ).
Example
dict = {} dict['one'] = "SOURCECODEHERO" dict[2] = "PYTHONFORFREE" tinydict = {'name': 'Glenn','code':2159, 'dept': 'IT'} print (dict['one']) # Prints value for 'one' key print (dict[2]) # Prints value for 2 key print (tinydict) # Prints complete dictionary print (tinydict.keys()) # Prints all the keys print (tinydict.values()) # Prints all the values
Output
SOURCECODEHERO PYTHONFORFREE {'name': 'Glenn', 'code': 2159, 'dept': 'IT'} dict_keys(['name', 'code', 'dept']) dict_values(['Glenn', 2159, 'IT'])
Boolean Data Types in Python
The boolean data type is an in-built function that represents one of the two values it’s either True or False. A bool() function can be used to evaluate the value of any expressions and simply returns a True or False based on the results of the expressions.
Example
x = True # display the value of a print(x) # display the data type of a print(type(x))
Output
True <class 'bool'>
The program below is another example that evaluates expressions and returns the values and prints.
# Returns false as x is not equal to y x = 10 y = 6 print(bool(x==y)) # Following also prints the same print(x==y) # Returns False as a is None x = None print(bool(x)) # Returns false as a is an empty sequence x = () print(bool(x)) # Returns false as a is 0 x = 0.0 print(bool(x)) # Returns false as a is 10 x = 10 print(bool(x))
Output
False False False False False True
Conversion Data Type in Python
Conversions sometimes needed to be performed between in-built Python programming data types. Converting data between different data types can be done by the use of the type name as a function.
int conversion
The following program below is an example to convert a number, float, and string into an integer data type.
x = int(2) # x will be 2 y = int(3.2) # x will be 4 z = int("4") # z will be 4 print (x) print (y) print (z)
Output
2 3 4
float conversion
The following program below is an example to convert a number, float, and string into a float data type.
x = float(2) # x will be 2.0 y = float(3.2) # x will be 3.2 z = float("4") # z will be 4.0 print (x) print (y) print (z)
Output
2.0 3.2 4.0
string conversion
The following program below is an example to convert a number, float, and string into a string data type.
x = str(2) # x will be "2.0" y = str(3.2) # x will be "3.2" z = str("4") # z will be "4.0" print (x) print (y) print (z)
Output
2 3.2 4
Data Type Conversion Functions in Python
There are some in-built functions that perform a conversion from single data to another and these functions will return a new object which represents the converted value.
Function | Description |
int(x [,base]) | Converts x to an integer. base specifies the base if x is a string. |
long(x [,base] ) | Converts x to a long integer. base specifies the base if x is a string. |
float(x) | Converts x to a floating-point number. |
complex(real [,imag]) | Creates a complex number. |
str(x) | Converts object x to a string representation. |
repr(x) | Converts object x to an expression string. |
eval(str) | Evaluates a string and return an object. |
tuple(s) | Converts s to a tuple. |
list(s) | Converts s to a list. |
dict(d) | Creates a dictionary. d must be a sequence of (key,value) tuples. |
frozenset(s) | Converts s to a frozen set. |
chr(x) | Converts an integer to a character. |
unichr(x) | Converts an integer to a Unicode character. |
ord(x) | Converts a single character to its integer value. |
hex(x) | Converts an integer to a hexadecimal string. |
oct(x) | Converts an integer to an octal string. |
Summary
In summary, you have read about Python Datatype. We also discussed in this article what is Python datatype, basic data types, data type conversion functions, and different types of data types,
I hope this article about Datatype In Python could help you a lot to continue pursuing learning this powerful programming language.
If you want to learn more check out my previous and latest articles for more career-changing articles.