Data Types in Python

Data types is one of the most important chapters in python programming. We are always in need for storing, manipulating and operating multiple values. In order to do that, we use three distinct data types:
  1. Lists
  2. Tuples
  3. Dictionaries
We're going to learn how and when to use each of these types, what is their basic syntax and how to implement functions that are provided with their usage.

Lists

Lists is one of my favourite data types because they are dynamic (can be changed easily) and can store a variety of different types of variables. Example: You can insert an integer, a float and a string value.

Basic Syntax

>>>   listName = []
>>>   listName = ['pythonside', 4.56, 35]
>>>   del listname   Delete a list

Try it!

Define a list with the name myList and store the values to the following order: 4563, 'Williams', 34.642, 87j.
?

List Operations and Indexes

When operating with lists, we need to be able to adjust, remove and insert elements if necessary. In order for you to become more familiar with the operations, I'm going to list a series of functions used for manipulating lists and elements, but first, we need to get our hands around indexes. Every list, contains indexing ids or position ids for each distinct element that holds. Assume list with the name ourList:

Elements: 1,2,3,4,5,6,7
Indexes - Position id: 0,1,2,3,4,5,6
Reverse - Position id: -7,-6,-5,-4,-3,-2,-1

By looking this chart we can see that the first position of element 1, has an index of 0, which is always the case. Every first element of a list has an index of 0 and every last element of a list has an index of -1. Index is the position. Reverse indexes are the same. We start counting from the end to the start from -1, -2, -3, -4. Some useful functions that you need to know:

Accessing a value at position 0

>>>   listname[0]
'pythonside'

Change a value at position 0

>>>   listname[0] = 'YouChanged'
>>>   listname[0]
'YouChanged'

You can isolate elements from a list using [:]

>>>   listname = [34, 56, 23, 56]
>>>   listname[0:3]
[34, 56, 23]'

Add lists

>>>   [2, 4, 6] + [5, 6, 19]
[2, 4, 6, 5, 6, 19]

Useful Function Notation

len(listname) Used for extracting the length of a list. Assume list with the name 'listname'. The len() function will return the number of elements that it contains. Example:

>>>   listname = [0 , 1, 2, 3, 4]
>>>   len(listname)
5

exercise-icon Try it!

Assume list with name Bananas = [0,2,4,5,6,2,4]. Apply the len() function as indicated.
?

listname.insert() is used for inserting specific element based on index-'position' given. This function has two arguments. You pass the index of the element and the new value that it is to be imported. Example:

>>>   listname = [0, 1, 2, 3, 4]
>>>   listname.insert(0, 10)
>>>   listname
[10, 0, 1, 2, 3, 4]

In this case, 0 is the index given and 10 is the new value. The first position of the list was been set with 10 without removing the previous 'first' positioned value.

exercise-icon Try it!

Assume list with name Bananas = [0,2,4,5,6,2,4]. Apply the insert() function as indicated. At index 3 of the list, insert a value 23.
?

listname.append() is used for appending-adding specific elements in the end of a list. The function has only one argument. Example:

>>>   listname = [0, 1, 2, 3, 4]
>>>   listname.append(10)
>>>   listname
[0, 1, 2, 3, 4, 10]

exercise-icon Try it!

Assume list with name Bananas = [0,2,4,5,6,2,4]. Apply the append() function as indicated. Append the number 298 into the list.
?

listname.index() is used for identifying an element's index or position based on its value. The function has only one argument. You enter the value (must be an element of the list) and you get its position (index) in return. Example:

>>>   listname = [65,43,77,23,76]
>>>   listname.index(43)
1     = "position 1"

exercise-icon Try it!

Assume list with name Bananas = [0,2,4,5,6,2,4]. Apply the index() function as indicated. Find the position (index) of number 6.
?

listname.pop() will remove an element from a list based on the index given. The function has only one argument. You only have to enter the index of the element you wish to remove. Example:

>>>   listname = [65,43,77,23,76]
>>>   listname.pop(2)
>>>   listname
[65, 43, 23, 76]

exercise-icon Try it!

Assume list with name Bananas = [0,2,4,5,6,2,4]. Apply the pop() function as indicated. Remove the element at index 5 from the corresponding list.
?

Extra Functions for Lists

Convert a string to a list using the list() function:
>>>   myStr = 'whatsup'
>>>   list(myStr)
['w', 'h', 'a', 't', 's', 'u', 'p']

Min & Max of a list using max() and min() functions:
>>>   alist = [2, 34, 9, 7, 33, 56, 66]
>>>   max(alist)
66
>>>   min(alist)
2

Compare two lists based on elements using cmp(list1, list2) funnction. if list1 < list2 will return -1, if list1==list2 will return 0, and if list1 > list2 will return 1.
>>>   a = [1,2]
>>>   b = ['hey', 'you']
>>>   cmp(a, b)
-1

More functions can be found: Python 3 Docs | Python 2 Docs

Tuples

Tuples are similar data types to lists. They can store data like lists but they can't be modified. Their syntax and operations are slightly different from those of a typical list. Tuples can be used for coordinate sets, unique sets (database records) or even as key sets for an encryption-decryption application.
  • Basic Syntax & Functions

    >>>   sampleTuple = ()
    >>>   sampleTuple = (23.4, 98.5)
    >>>   del sampleTuple   Delete a tuple
  • Indexes

    >>>   sampleTuple = (23.4, 98.5)
    >>>   sampleTuple[1]   "What's the value at position 1?"
    98.5
    >>>   sampleTuple.index(98.5)   "What's the position of value 98.5?"
    1
  • Length of a Tuple

    >>>   sampleTuple = (23.4, 98.5)
    >>>   len(sampleTuple)   "How many elements are there?"
    2
  • Count/Find element of a Tuple

    >>>   sampleTuple = (23.4, 98.5)
    >>>   sampleTuple.count(23.4)   "How many elements have a value of 23.4?"
    1

  • You can always use the conversion function tuple(), similarly to the list conversion. Functions cmp(tuple1, tuple2) and min(tuple)/max(tuple) can also be used with no problems at all.
Let's write some code!

Try it!

Create a tuple named tupCoord with four elements 45.653, 87.231, 98.876 and 194.545.
  1. Take the index of 2 with the corresponding operation (see above:'Indexes').
  2. Declare a new variable named lengthTup and set it to the length of the tuple using len() function.
  3. Find out how many elements have a value of 98.876 and store it to a new variable named searchTup.
  4. Print the lengthTup variable

?

Dictionaries

A dictionary is composed from a series of keys (any defined type) pointing to certain values, strings, lists or etc. Dictionaries can be incredibly useful because gives us the ability to access specific elements from a given key values, which can represent an input from a user, or an id from a database. A dictionary if used correctly, can be far more superior than regular, or parallel lists. If we had a list and wanted to set a unique id for each element, (for calling it later), we'd have to use a parallel list which will point our initial one (plist[0] => list[0], plist[1] => list[0], etc).

Basic Syntax

>>>   myDict = { 'Name': "Walter", 'Age': 54 }
>>>   del myDict   Delete entire dictionary

Accessing the value based on its key

>>>   myDict['Name']
'Walter'
>>>   myDict['Age']
54

exercise-icon Try it!

Create a dictionary named carLnd with keys 'Brand' and 'Production'. Set the value of 'Brand' to 'Audi' and value of 'Production' to 1996.
?

Dictionary Functions & Operations

You can use some the functions already mentioned from the lists and tuples, but not all of them. Let's begin with len():

>>>   myDict = { 'Name': "Walter", 'Age': 54 }
>>>   len(myDict)
2

Insert new keys and elements into your dictionary

>>>   myDict = {'Age': 54, 'Name': 'Walter'}
>>>   myDict['Studies'] = 'Drop Out'
>>>   myDict
{'Studies': 'Drop Out', 'Age': 54, 'Name': 'Walter'}

Update element values or remove specific elements

  • Update element

    >>>   myDict['Age'] = 64
    >>>   myDict
    {'Studies': 'Drop Out', 'Age': 64, 'Name': 'Walter'}

  • Remove specific element

    >>>   del myDict['Age']
    >>>   myDict
    {'Studies': 'Drop Out', 'Name': 'Walter'}

exercise-icon Try it!

Assume dictionary Cars = { 'Brand': 'Audi', 'Age': 120, 'Month': 4 }. Update element 'Brand' to 'Fiat' and delete element 'Month' entirely. Use single quotes!
?

Dictionaries - Monitoring

When working with dictionaries, it's important to know how to view keys or extract values on demand. There are some functions which allow us to do these things easily, without applying multiple iterations or developing crazy sized scripts.

>>>   Cars = { 'Brand': 'Audi', 'Age': 120, 'Month': 4 }

View keys
>>>   Cars.viewkeys()
dict_keys(['Brand', 'Age', 'Month'])

View elements - Keep in mind that viewitems() function, returns us the keys and values as multiple tuples, which makes sense since each key is pointing its specific and unique value.

>>>   Cars.viewitems()
dict_items([('Brand', 'Audi'), ('Age', 120), ('Month', 4)])

get() Function - The get() function can return a value based on given key.
You don't need squared parenthesis. Examples bellow:

>>>   Cars.get('Brand')
'Audi'
>>>   Cars.get('Age')
120

pop() Function - The pop() function will remove an element with its key entirely, but first will return key's value. Exaple:

>>>   Cars = { 'Brand': 'Audi', 'Age': 120, 'Month': 4 }
>>>   Cars.pop('Age')
120
>>>   Cars
{'Brand': 'Audi', 'Month': 4}

exercise-icon Try it!

Assume dictionary Cars = { 'Brand': 'Audi', 'Age': 120, 'Month': 4 }. Get the Month value, remove 'Brand' element entirely but show its value first and finally, display all the keys inside. Use single quotes!
?

exercise-icon Pop Quiz

Create a list named Rates with elements 2,3,4,5,6,7,8,10. Change value 7 with the string 'Quiz'. Add an element in the end of the list named 'PythonSide'. Sort the list and then deleted entirely. Create tuple named numLogs with elements (2.34, 87.93, 44.2, 3, 98.2, 0, 3). Find out how many values of 3 exist using the proper function. Write down the position of 98.2 and finally delete the whole tuple. Vehicles' department asked us to create a dictionary named CCodes with elements 'Fiat' with value 98, 'Ford' with value 95 and 'Pagani' with value 11. We've been told to return all brands (Just the brands - view monitoring section) onto the main screen for evaluation. We are required to get the value of 'Ford' and afterwards when the evaluation has ended to erase the dictionary.

Note: Use single quotes, when quotes are needed

?