Python Basic Data Type

Introduction to Python #1

Python Data Type

All of the Python data types are the object, so no matter whether the type is str, int or float, Python variables store the address of the values (literals). Which address the value is stored can be found using id() function.

1. Numbers

There are three number types, integer (e.g. 1, -2, 100), floating-point numbers (e.g. 0.01, 4e5), and complex numbers (e.g. 1+1j, 9j). type() function tells you which type the variable are. To create int, float, complex object explicitly, int(), float(), complex() constructors can be used.
Note: Impossible to convert complex numbers to real numbers using int() or float().

>>> type(2)
<class 'int'>
>>> type(0.01)
<class 'float'>
>>> type(4e5)
<class 'float'>
>>> type(9j)
<class 'complex'>

Arithmetic Operations

Python has the same style of arithmetic operations. However, there are a few things we need to care about. First, the difference between '/' and '//' is that/ return the integer and fraction part while // discarded the fraction part and returns the integer part. Also, Python does not have ++or -- operator, so every time you need increment or decrement, you have to use a += 1 or a -= 1.

Manipulation Expression
Summation 1 + 2
Subtraction 2 - 1
Multiplication 2 \** 3
Division 4 / 3 or 4 // 3
Reminder 4 % 3
Power 2 *** 3

Example

>>> 1 + 2
3
>>> 2 - 1
1
>>> 2 * 3
6
>>> 4 / 3
1.3333333333333333
>>> 4 //3
1
>>> 4 % 3
1
>>> 2**3
8

2. Strings

str is a data type that deals with string data in Unicode. Strings are enclosed by " " or ' '. In Python, the series of characters are saved in the object called sequence, a type of Python object that aligns objects in a certain order. Thus, like C++, Strings in Python can be manipulated like an array object.

Example

❯ py
Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Kojiro Asano"
>>> name
'Kojiro Asano'
>>> name[0]              # The first character of 'Kojiro Asano'
'K'
>>> name[1]              # The second character of 'Kojiro Asano'
'o'
>>> name[-1]             # The last character of 'Kojiro Asano'
'o'
>>> name[-2]             # The second last character of 'Kojiro Asano'
'n'
>>> name[0:6]            # The 0 to 6 characters of 'Kojiro Asano'
'Kojiro'
>>> name[:6]             # Same expression of name[0:6]
'Kojiro'

However, unlike other programming languages, Python does not allow overwriting the contents of String like name[0] = k;. If you want to change the contents of Strings, replace( ) is useful. By using +, Strings can be concatenated, and by using * and number, Strings are repeated as many as you want. str is immutable.


>>> name = "Kojiro Asano"
>>> name[0] = 'k'             # This is not allowed.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> name.replace('K', 'k')     # This is allowed
'kojiro Asano'
>>> 'Mr.' + name               # Concatnating 'Mr. ' and ' Kojiro Asano'
'Mr.Kojiro Asano'
>>> name * 5                   # Repeating 'Kojiro asano' five times
'Kojiro AsanoKojiro AsanoKojiro AsanoKojiro AsanoKojiro Asano'

3. Bool

bool is the data type which deals with Boolean values, true and false. In Python empty values (0, 0.0, 0+0j,' ', [ ], ( ), { }, set(), None) are considered to be falsy value. Whether values are True or false cannot be found with == operator because those values such as 0.0, [] are not exactly equivalent to False, so if you want to find the values are falsey or truthy, you need to use bool().

>>> bool(0)
False
>>> bool([])
False
>>> bool( )
False
>>> bool({})
False
>>> bool(())
False
>>> bool(set())
False
>>> bool(None)
False

4. List

List is also one type of sequence object. List can store any type of objects such as integer, float, and strings. Each element is distinct by , and the whole element is enclosed by '[' ']'. Each element is indexed from 0 to number of element - 1. Python does not allow to access the element of the list with an index out of range.
Unlike String one, the list allows overwriting. For instance, list[1] = 150 is allowed. After this operation, the list will contain ['Python', 150, 0.5].

>>> list = ['Python', 100, 0.5]
>>> list
['Python', 100, 0.5]
>>> print(list[0]) # access list[0]
Python
>>> list[1] = 150 # overwrite list[1] from 100 to 150
>>> print(list)
['Python', 150, 0.5]

You cannot access the element out of range, but utilizing the methods (e.g. append(), insert(), pop(), remove()), you can either extend or shrink the list. Also, simply using +, you can concatenate the lists. Or using extend() method, you can just extend the existing list.

>>> list = [1, 2, 3]
>>> list.append(4) # appending the value 4
>>> list.insert(0, 0) # insert the 0 at the index of 0
>>> list
[0, 1, 2, 3, 4]
>>> list.insert(3, 2.5) # insert 2.5 at the index 3
>>> list
[0, 1, 2, 2.5, 3, 4] 
>>> list.pop(3) # delete the element with index 3
2.5
>>> list
[0, 1, 2, 3, 4]
>>> list.remove(2) # another way to remove element choosing the element you want to delete
>>> list
[0, 1, 3, 4]

>>> one = [1, 2, 3]
>>> two = [4, 5, 6]
>>> one + two   # concatenate the lists
[1, 2, 3, 4, 5, 6]
>>> one.extend(two)
>>> one
[1, 2, 3, 4, 5, 6]

Also, in Python, there is a sorting method sort() and reverse(). Once you use sort() or reverse(), the order in the list has been changed. However, sort() and reverse() can be used in the same type of data (you can use them with number and number or str and str).

>>> list = [3, 7, 9, 1, 6, 2] # unsorted
>>> list.sort() # sorting the list in descending order
[1, 2, 3, 6, 7, 9]
>>> list.reverse() # sorting the list in reverse order
>>> list
[9, 7, 6, 3, 2, 1]

>>> list = ["string", 1, 0.33] # comparing different type of data
>>> list.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'

Also, sort() function supports the keyword argument. By using key, you can sort the list as you want. The key parameter is usually for functions.

>>> list = ["Python", "Javascript", "C++", "Java",]
>>> list.sort() # normal sort() function just sort the string list in alphabetic order
>>> list
['C++', 'Java', 'Javascript', 'Python']
>>> list.sort(key=len)
>>> list
['C++', 'Java', 'Python', 'Javascript']

>>> def reverselen(elem):
...     return -(len(elem))
...
>>> list.sort(key=reverselen)
>>> list
['Javascript', 'Python', 'Java', 'C++']
>>> sum([[1], [2, 3], [4], [5, 6, 7]], [])
[1, 2, 3, 4, 5, 6, 7]


5. Dictionary

Dictionary names the data and stores them. Dictionaries are collections of key-value pairs{key: value}. However, there are some restrictions.

  1. two keys have to be unique. Python does not allow {'one': 1, 'one': 2}.
  2. value can be mutable. However key must be immutable, meaning the variable and list type cannot be used as a key.
<VARIABLE> = {<KEY1>: <VALUE1>, <KEY2>: <VALUE2>, <KEY3>: <VALUE3>... }

Example of Creating, Adding, Deleting

To add the element in the dictionary, you need to use <DICTIONARY>[<KEY>] = <NEW VALUE>. To delete the element in the dictionary, <DICTIONARY>.pop(<KEY>).

states = {"AL": "Alabama", "CA":"California", "FL":"Florida", "Mississippi":"MN", "NJ":"New Jersey", "TX":"Texas", "Washington":"WA"}
>>> states["AL"] # Accessing the value using key "AL"
'Alabama'
>>> states["UT"] = "Utah" # Adding the value with "UT"
>>> states
{'AL': 'Alabama', 'CA': 'California', 'FL': 'Florida', 'Mississippi': 'MN', 'NJ': 'New Jersey', 'TX': 'Texas', 'Washington': 'WA', 'UT': 'Utah'}
>>> states.pop('CA') # deleting the value with 'CA'
'California'
>>> states
{'AL': 'Alabama', 'FL': 'Florida', 'Mississippi': 'MN', 'NJ': 'New Jersey', 'TX': 'Texas', 'Washington': 'WA', 'UT': 'Utah'}

Example of keys(), values(), and items()

>>> majors = {"EES": "Environmental Engineering Science", "EECS": "Electrical Engineering and Computer Sciences", "ME": "Mechanical Engineering"}
>>> for major in majors.keys():
...     print(major)
...
EES
EECS
ME
>>> for major in majors.values():
...     print(major)
...
Environmental Engineering Science
Electrical Engineering and Computer Sciences
Mechanical Engineering
>>> for major in majors.items():
...     print(major)
...
('EES', 'Environmental Engineering Science')
('EECS', 'Electrical Engineering and Computer Sciences')
('ME', 'Mechanical Engineering')


Any feedback or suggestions are always welcome!! I update (adding list section) on August 26 2022


Previous Article: Introduction to Python #0(Installing Python & PyCharm)

Did you find this article valuable?

Support Kojiro Asano by becoming a sponsor. Any amount is appreciated!