Python provides several built-in types for variables: number, tuple, string, bool, list, dictionary, sets, and None. Some of these types are immutable -- once we define them, we cannot change their value. These types are number, bool, tuple, and string. On the other hand, some of the built-in types are mutable and thus, can be changed once we define them. These types are list, dictionary, and set.
As the name suggests, the None type indicates a lack of value. It can be used in many scenarios; one example is that we can use it to test if no argument is passed to a function values.
Due to Python's flexible dynamic typing, we do not need to specify the type of a variable before using it. Due to dynamic typing a variable is not associative with a storage type for its entire lifetime and gets updated if a new value is assigned to an existing one.
Next, we provide an overview of some of these types. We will learn more about them in later sections.
Python provides two types to store numbers: int (integer) and float. We provide an example that uses an int and float variables. We use the type() function to retrieve the variable type. For this example and beyond we use Python 3.x.
[user@codingbison]$ python3 Python 3.2.1 (default, Jul 11 2011, 18:55:33) [GCC 4.6.1 20110627 (Red Hat 4.6.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> varX = 101 >>> print(type(varX)) <class 'int'> >>> >>> varX = 101.280 >>> print(type(varX)) <class 'float'> >>>
The number type allows us to do various numeric (arithmetic) operations like addition, multiplication etc.
>>> varX = 200 + 80 >>> print(varX) 280 >>> >>> varX = 5 * 3 >>> print(varX) 15 >>>
Numbers belong to the immutable type. This means that if we assign a new value to a variable, then the variable now points to a new number object and the earlier object remains unchanged. Thus, if we have "varX = 101" and then do "varX = 280", then we are able to change varX from "101" to "280" but the number objects "101" and "280" themselves remain unchanged! With the reassignment, varX simply starts to point to a new number object.
Further, since Python is dynamically typed, once we reassign a variable that holds an integer to some other variable type, then Python automatically updates the type of the variable. In the following example, when we assign a string to the varX variable that holds an integer value, then the type of the varX changes to string.
>>> varX = 101 >>> print(type(varX)) <class 'int'> >>> >>> varX = "Blue Whale" >>> print(type(varX)) <class 'str'> >>>
The integer type provides a common type to store both integers and longs (large numbers). This is a change with Python 3.0 since earlier, we had different types for these two (int and long). Also, Python does not provide any upper limit on the length of the value stored in an integer.
The next Python type is string type; a Python string is simply a finite ordered sequence of characters; these characters can be letters, numbers (from 0 to 9), white-space etc. A string value is text kept within quotes (single, double, or triple). Thus, we can define a variable (varStr) as 'varStr = "Blue whale"'.
>>> varStr = "Blue Whale" >>> >>> print(type(varStr)) <class 'str'> >>> print(varStr) Blue Whale >>> >>> varStr = 'Blue Whale' >>> print(type(varStr)) <class 'str'> >>> >>> varStr = '''Blue Whale''' >>> print(type(varStr)) <class 'str'> >>>
We can use the len() function to count the number of characters in the string sequence. Note that len() is a generic function that is applicable to other Python sequence types as well like lists, tuples, and dictionaries.
We can refer to individual character elements of a string using their index. Like lists, we can do that using the 0-based index (offset). Thus, varStr[0] refers to the first character of the varStr ('B'), varStr[1] refers to the second character ('l'), and so on.
>>> varStr = "Blue Whale" >>> >>> print(varStr) Blue Whale >>> print(len(varStr)) 10 >>> print(varStr[0]) B >>>
Like numbers, Python strings are also immutable. This means that when we reassign a new value to an existing variable, then the variable now points to the new value -- but the original string object remains unchanged. Also, when we try to change the values of individual characters, then Python would throw an error.
>>> varStr[0] = 'G' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment >>>
Strings support a host of useful methods that allow us to carry various useful string-related tasks. We will revisit strings in a later section and cover these methods in more detail (provide the URL here).
Python supports boolean type ("bool" class) and it provides two values: True and False. In terms of value, True equals 1 and False equals 0. We can use int() cast to convert these values into integer.
>>> varInt = int(varBool) >>> varBool = True >>> print(type(varBool)) <class 'bool'> >>> >>> varBool = False >>> print(type(varBool)) <class 'bool'> >>> >>> varInt = int(varBool) >>> print(varInt) 0 >>> varBool = True >>> varInt = int(varBool) >>> print(varInt) 1 >>>
When we define a Python variable, the variable represents a single unit of data. However, sometimes, an application may need to store a sequence of data and its logic may need to perform a task on the entire series of data. For such use-cases, Python provides a new type: Python lists. We can define Python lists using square brackets ("[" and "]"). List elements do not necessarily have to be of the same type.
Elements of a list are identified using a 0-based indexing. The first element has an index of 0, the second one has the next index of 1, and the last element has an index of N-1.
Next, let us go through an example that defines a list and accesses its elements.
>>> varList = [101, "Blue Whale", "Sea Turtle", 101.280] >>> print(type(varList)) <class 'list'> >>> >>> print(varList) [101, 'Blue Whale', 'Sea Turtle', 101.28] >>> >>> print(varList[1]) Blue Whale >>>
Lists are mutable. Thus, we can change elements of a list. In the following example, we update the first element of the list.
>>> varList = [101, "Blue Whale", "Sea Turtle", 101.280] >>> print(varList) [101, 'Blue Whale', 'Sea Turtle', 101.28] >>> >>> varList[0] = 680 >>> >>> print(varList) [680, 'Blue Whale', 'Sea Turtle', 101.28] >>>
We will revisit lists in a later section.
Python tuples allow us to hold a sequence of data elements. We can define a tuple using a set of elements separated by commas and enclose them within parenthesis. Thus, 'varTuple = (101, "Blue Whale", "Sea Turtle")' defines a varTuple that has three elements. The tuple elements need not be of the same type -- yet another example of Python's flexibility!
Like lists and strings, we can access tuple elements using a 0-based indexing. The first element has an index of 0, the second one has the next index of 1, and the last element has an index of N-1. We can use these indexes to navigate the tuple.
>>> varTuple = (101, "Blue Whale", "Sea Turtle") >>> >>> print(type(varTuple)) <class 'tuple'> >>> >>> print(varTuple) (101, 'Blue Whale', 'Sea Turtle') >>> >>> print(varTuple[1]) Blue Whale >>>
Unlike lists, tuples are immutable -- in other words, elements of tuples cannot be modified. If we reassign a new tuple to a tuple variable, then the variable starts to point to a new tuple and leaves the original tuple object intact! Since tuples are immutable, if we attempt to update its elements, then Python will throw a TypeError.
>>> varTuple[1] = "Tiger Shark" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>>
Being immutable has its own advantages. First, it means that when we pass a tuple to functions, we can be certain that its value would remain unchanged -- Python does not have a "constant" qualifiers and so using tuples (or other immutable types) for such cases can provide us with this behavior. Second, the keys for Python dictionaries must be immutable types and so this allows us to use tuples as dictionary keys.
Python dictionaries provide a mechanism to store (key, value) mappings. With dictionary, we can retrieve a stored value using its key. This is in contrast to a list, where elements are retrieved based on indices. Like lists, the stored values do not need to be of the same type. The same applies to dictionary keys as well.
We can define a dictionary by enclosing key/value pairs within a pair of braces, where each key is separated from its value using a colon. Thus, 'varDict = {"highway101": 101, "guanaco": "Lama guanicoe"}' defines a dictionary (varDic) that has two key/value pairs. We can also start with an empty dictionary (as in 'varDict = {}') and keep on adding elements to it (as in 'varDict["guanaco"] = "Lama guanicoe"'). Adding elements to a dictionary is okay since dictionaries (like lists) are mutable.
>>> varDict = {"highway101": 101, "guanaco": "Lama guanicoe"} >>> print(type(varDict)) <class 'dict'> >>> >>> print(varDict) {'highway101': 101, 'guanaco': 'Lama guanicoe'} >>> >>> print(varDict["highway101"]) 101 >>>
Since elements of a dictionary are referred using the key, trying to attempt to retrieve an element using an index would lead to an error!
>>> print(varDict[1]) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 1 >>>
The keys for the dictionary must be immutable -- attempting to use mutable keys would lead to an error. Thus, if we were to use a list as a key, then Python would throw a TypeError. If we must use a sequence as a dictionary key, then we can always use a tuple.
>>> varList = [1, 2, 3] >>> >>> varDict[varList] = 123 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> >>> varTuple = (1, 2, 3) >>> varDict[varTuple] = 123 >>> >>> print(varDict) {'highway101': 101, 'guanaco': 'Lama guanicoe', (1, 2, 3): 123} >>>
We will revisit dictionaries in a later section.
Lastly, Python provides several type-related built-in functions: int(), float(), and str().
The int() function returns an integer value when we pass an integer as a string (e.g. "101"). However, if the string cannot be represented as an integer (e.g. "highway101"), then Python will throw an error! The string must also not be of the form float as well (e.g. "101.280"), Python will throw a ValueError.
The float() function returns a float value when we pass a number (float or int) as a string (e.g "101" or "101.280"). Once again, if the string cannot be represented as a number (int or float), then Python will throw a ValueError.
>>> varStr = "580" >>> >>> print(type(varStr)) <class 'str'> >>> print(varStr) 580 >>> varInt = int(varStr) >>> print(type(varInt)) <class 'int'> >>> print(varInt) 580 >>> varInt = int("Blue Whale") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'Blue Whale' >>> >>> varFloat = float("101.280") >>> print(type(varFloat)) <class 'float'> >>> print(varFloat) 101.28 >>>
The str() function converts other types into a string format. This can be a handy function, when we are trying to concatenate a non-string value with a string.
>>> varInt = 10 >>> varStrNum = str(varInt) >>> print(type(varStrNum)) <class 'str'> >>> >>> varStr = varInt + " Blue Whales" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> >>> varStr = str(varInt) + " Blue Whales" >>> print(varStr) 10 Blue Whales >>> >>> varTuple = (101, 280, 380) >>> >>> varStr = varTuple + " is a tuple" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate tuple (not "str") to tuple >>> >>> varStr = str(varTuple) + " is a tuple" >>> >>> print(varStr) (101, 280, 380) is a tuple >>>
Python also provides list() function that can take a sequence (say, a tuple) and convert it into a list.
>>> varTuple = (101, 280, 380) >>> print(varTuple) (101, 280, 380) >>> >>> varList = list(varTuple) >>> print(type(varList)) <class 'list'> >>> >>> print(varList) [101, 280, 380] >>>
Similarly, Python provides tuple() function that can take a sequence (say, a list) and convert it into a tuple.
>>> varList = [101, "Blue Whale", 280, "Sea Turtle"] >>> print(varList) [101, 'Blue Whale', 280, 'Sea Turtle'] >>> >>> varTuple = tuple(varList) >>> print(type(varTuple))o <class 'tuple'> >>> >>> print(varTuple) (101, 'Blue Whale', 280, 'Sea Turtle') >>>
Lastly, Python also provides bool() function that can take any value and convert it to True or False. Basically, values like 0, None, False, empty tuple, empty dictionary, empty list, empty string have a value of False. Everything else is considered True.
>>> varInt = 237 >>> varBool = bool(varInt) >>> print(type(varBool)) <class 'bool'> >>> print(varBool) True >>> >>> varStr = "Blue Whale" >>> varBool = bool(varStr) >>> print(type(varBool)) <class 'bool'> >>> print(varBool) True >>> >>> varNone = None >>> varBool = bool(varNone) >>> print(type(varBool)) <class 'bool'> >>> print(varBool) False >>>