Everything You Need To Know About Python Data Types & Variables

0 Comments

Starting with the Basics

In a nutshell, a variable is a memory location where you can store a value. This value may or may not change in the future. In Python, the declare a variable, you just have to assign a variable to it.

For example:

x = 5

x is assigned the integer value of 5. There are no additional commands or type declaration, unlike other programming languages.

You can also perform operations on these variables using arithmetic operators (eg: + ,  , * , and %). If you declare a variable without assigning a value to it, it will give you a NameError .

Here is an example of what the error looks like if we declare x without any assignments:

Traceback (most recent call last):  
File "<pyshell#0>", line 1, in <module>    
xNameError: name 'x' is not defined

Variables in Python are case sensitive, which means that y is considered as different from Y.

Variable Data Types

There are 6 data types in Python and they are:

  1. Numbers
  2. Strings
  3. Lists
  4. Dictionaries
  5. Tuples
  6. Sets

There is one more data type called Range — but that is mainly used when we are iterating through values such as in for loops.

Let’s go through each Python data type quickly.


Number

number are numerical data types that mainly have numerical values. In number, we have 4 different data types — integer, float, complex , and boolean.

Here’s a summary of each data type.

integer

Takes a whole numerical value. Looks something like this:

x = 10
y = 12
z = 45

float

A float takes a numerical value with decimal points. It looks something like this:

x = 10.45
y = 3.98
z = 239.29084

complex

A complex data type involves an imaginary number part which is always represented as j. For example:

x = 98j
y = 98.78j
z = 982.9388j

The imaginary number part needs to be j or else you will get SyntaxError: invalid syntax.

boolean

A boolean only returns a true or false value. This means there is always some sort of comparison involved. Here are some examples:

x = 1
y = 2
x > y
# will output False

Other notes:

type() is a Python function that lets you check the type of a variable. For example:

x = 1
type(x)
# will output <class 'int'>

x = 1.29
type(x)
# will output <class 'float'>

x = 1.3j
type(x)
# will output <class 'complex'>

x = 1
y = 2
num = x < y
type(num)
# will output <class 'bool'>

String

String is an alpha data type that is writing in single '' or double "" quotes. It can contain numbers and special characters but they will be evaluated as actual letters rather than the numerical values. Here are some examples:

x = 'hello'
y = "moo cow"
z = input()

print(x, y, z)

String values are accessible viable an index number. To check the length of a String, you can use len(). For example:

name = 'DottedSquirrel.com'
len(name)
# len(name) will return 18 as a value

To access a specific letter based on the index number, you can do so using [] . Here is an example:

name = 'DottedSquirrel.com'
name[5]
# name[5] will return 'd'

It is also good to note that index numbers starts the count at 0. Strings are immutable in that you can’t change the indexed value. For example, you can’t do this:

name = 'DottedSquirrel.com'
name[2] = 'q'

This will give the following error:

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name[2] = 'q'
TypeError: 'str' object does not support item assignment

You can also access the index of a String as a range. Here’s how you do it:

name = 'DottedSquirrel.com'
name[2:8]
# name[2:8] will return 'ttedSq'

If the range is bigger than the actual String length, it will still work. For example:

name = 'DottedSquirrel.com'
name[2:24]
# name[2:24] will return 'ttedSquirrel.com'

To access your String from the end, you can use a negative number. For example:

name = 'DottedSquirrel.com'
name[-3]
#name[-3] will return 'c'

To turn your Python String into uppercase, you can use .upper().

name = 'DottedSquirrel.com'
name.upper()
# name.upper() will return 'DOTTEDSQUIRREL.COM'

To turn your Python String into lowercase, you can use .lower()

name = 'DottedSquirrel.com'
name.lower()
# name.lower() will return 'dottedsquirrel.com'

List

A list is an array that is changeable and ordered, with duplicates allowed. This means that it has indexes, just like Strings. You can declare different data types inside a list. Here is how you declare a list:

someList = [10,20,30,30,40,50,50,'dottedsquirrel.com']

You can access the values in the list using the same syntax as demonstrated in the String section.

someList[2]
# will return '30'
someList[2:5]
# will return [30, 30, 40]
someList[-2]
# will return '50'
someList[2:-2]
# will return [30, 30, 40, 50]

Lists are mutable. This means that you can update the individual content within the list using its index number.

someList[2] = 'meow'
# your new list will look something like this: 
# [10, 20, 'meow', 30, 40, 50, 50, 'dottedsquirrel.com']

You can also add a value using .append() . This will add the value at the end of the list.

someList.append(10)
# your new list will look something like this: 
# [10, 20, 'meow', 30, 40, 50, 50, 'dottedsquirrel.com', 10]

If you want to add a value at a particular location inside your list. You can do so using the insert() function. insert() takes two parameters: the index of where you want to put your new value, and the value itself.

For example:

someList.insert(3, 'hello')
# your new list will look something like this:
# [10, 20, 'meow', 'hello', 30, 40, 50, 50, 'dottedsquirrel.com', 10]

You can also reverse your list by using reverse() function. Here is what it looks like:

someList.reverse()
# your new list will look something like this:
# [10, 'dottedsquirrel.com', 50, 50, 40, 30, 'hello', 'meow', 20, 10]

Dictionary

A Python dictionary is similar to a list where it is unordered, can be changed, and indexed. However, the major difference is that there are no duplicate entries allowed. Python dictionaries come as key-pair values, where the key is always unique. You can have either a number or String value as your key.

Here is an example:

courses = {1: 'python', 2: 'data science', 'third': 'JavaScript'}

You can access the value by using the key as the index. For example:

courses['third']
# this will return 'JavaScript'

You can also use the get() function to access the data inside your key-value pair. Here is an example:

courses.get('third')
# this will return 'JavaScript'

To update your value, you can do so like this:

courses['third'] = 'machine learning'
# your new Python dictionary will look like this:
# {1: 'python', 2: 'data science', 'third': 'machine learning'}

You can also add new key-value pair through assignment. Here is an example:

courses['fourth'] = 'hadoop'
# your new Python dictionary will look like this:
# {1: 'python', 2: 'data science', 'third': 'machine learning', 'fourth': 'hadoop'}

Tuple

A tuple in Python is an ordered list that cannot be changed. Unlike a dictionary, duplicates are allowed. Tuples are immutable like a String. Here is what a tuple looks like in Python:

animals = ('tiger', 'lion', 'seal', 'seal')

Tuples are indexed which means you can access it via an index number. Here is an example:

animals[2]
# this will return 'seal'

Because tuples are immutable, which means you cannot change it, there’s not that many operations you can perform on a tuple. You can count the number of duplicate values using count()

animals.count('seal')
# this will return 2

Set

A Python set is a collection just like Dictionaries and Tuples, but it is unordered with no duplicates entries. Here is an example:

animals = {'tiger', 'lion', 'seal', 'seal'}
# if you print animals, your set will look like this:
# {'tiger', 'lion', 'seal'}

Sets are mutable but because they are unordered, it means that there is no indexing. As a result, you can’t access or change elements inside a set.


Range & Miscellaneous Things

range() is a function used whenever we are iterating through values. For example, we can quickly create a list with iterated values like this:

list(range(10))
# this will return
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can make a list with multiple data types. For example:

a = [1,2,3,4]
b = {1,2,3,4}
c = [a,b]
# c will return
# [[1, 2, 3, 4], {1, 2, 3, 4}]

This lets you decide which parts of your data are mutable and which parts are not.


Type Conversion

Let’s say you have two pieces of data that are two different types. You need them to be the same type in order to perform operations on them. For example:

a = 'hello'
b = 2
a + b
# a + b will produce a TypeError

Here is the list of functions available for type conversion:

int() 
str()
float()
tuple()
list()
set()
dict()

Here is an example of how to use it:

a = 'hello'
b = 2
a + str(b)
# this will produce 'hello2'

Let’s take a look at another example:

animals = {'tiger', 'lion', 'seal', 'seal'}
list(animals)
# this will turn animals into a list
# ['lion', 'tiger', 'seal']

Cheatsheet and Summary of Python Data Types & Variables