Data Types | Data Structures

Table of contents

  1. Python Course-Part 01-Getting Started with Python| Development environment
  2. Python Course-Part 02-Getting Started with Python| Basics
  3. Python Course-Part 03-Data Types | Data Structures
  4. Python Course-Part 04-Control Structures
  5. Python Course-Part 05-Functions
  6. Python Course-Part 06-Database Access

1. Numerical Data Types

In Python numerical data types are:

  • point numbers: float
  • booleans numbers: bool
  • complex numbers: complex
Output:
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'complex'>

1.1 Arithmetic Operations

Arithmetic operations are:

  • Addition: x+y
  • Subtraction: x-y
  • Multiplication: x*y
  • Division: x/y
  • Power: x**y
  • Remainder of integer division: x%y
  • Integer division: x//y
Output:
Variable x: 7
Variable y: 3
Negation -x: -7
Addition x+y: 10
Subtraction x-y: 4
Multiplication x*y: 21
Division x/y: 2.3333333333333335
Power x**y: 343
Remainder of integer division x%y: 1
Integer division x//y: 2

1.2 Comparison Operators

For the data types int, long, float and boolean the following comparison-operators are defined:

  • ‘!=’ If values of two operands are not equal, then condition becomes true
  • ‘>’ If the value of left operand is greater than the value of right operand, then condition becomes true
  • ‘<’ If the value of left operand is less than the value of right operand, then condition becomes true
  • ‘>=’ If the value of left operand is greater than or equal to the value of right operand, then condition becomes true
  • ‘<=’ If the value of left operand is less than or equal to the value of right operand, then condition becomes true
Output:
a==b: False
a==d: True
a!=d: False
a<=d: True
b>c : True
c>d : False

1.3 Boolean Types

The boolean type belongs to the numeric types, all arithmetics operators can be applied to it. The value of a boolean variable can only be True (1) or False (0). In addition to the arithmetic operations for boolean, also the logical operators not , and (&) and or(|) are defined.

Output:
True
False
True
# or arithmetic operations with logical operators
True
False
True

1.3 Cast Numeric Types

The type of a variable x can be casted into a new one by typname(x)

Output:
Initial type of x: <class 'int'>
Type after float cast: <class 'float'>
Type after int declaration: <class 'int'>
Type after float declatation: <class 'float'>
Type after after int cast: <class 'int'>
Type after boolean cast: <class 'bool'>

2. Sequential Data Types

Sequential Data Types in Python contain sequences of elements. The following types belong to the category of sequential data types:

  • tuple
  • list
  • xrange objects
  • buffer
  • bytearray

2.1 String

A string is a sequence of characters. Strings can be defined within single, double or triple quotes.

2.1.1 Accessing string components

The components of strings are characters. Each component of a string-variable can be accessed by his index or index range. In Python the first index of a data type, is always 0.

Output:
First element of str1 is m
The first 2 elements of str1 are: myThe subsequence containing the 3rd, 4th, 5th, 6th, 7th an 8th element of s3 are: firstThe last character of str3 is gThe last 6 characters of str3 are: string

2.1.2 String operations

A list of all methods for string operations is available at the official Python documentation.

2.1.3 Concatenate strings

As shown in the code below:

  • \n yields a line -break
Output:
my first string my second string
my first string my second string
my first string
my second string

2.1.4 Determine the length of a string

Output:
15

2.1.5 Index of first occurence of characters in a string

Output:
3
9

2.1.6 Replicate strings

Output:
'abcdefg abcdefg abcdefg abcdefg abcdefg '

2.1.7 Count fequency of characters in a string

Output:
1
2

2.1.8 Characters are contained in strings

Output:
my first string
True
True
True
False
True

2.2 Lists

In Python lists can contain elements of different type. Same as the type string, the type list also belongs to the category of sequential types. Lists can be generated for example by writing the elements of the list comma separated into square brackets

Output:
[1, 2, 3.4, 'string1', False, ['a', 'b', 'c']]
<class 'list'>
[]
<class 'list'>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
<class 'list'>
[30, 32, 34, 36, 38]
<class 'list'>

2.2.1 Accessing list elements

Same as with strings, each component of a list, can be accessed by a index. Multiple list elements can be sliced by an index range.

Output:
[1, 2, 3.4, 'string1', False, ['a', 'b', 'c']]
3.4
False
[2, 3.4, 'string1']
['string1', False, ['a', 'b', 'c']]
b

2.2.2 Editing Lists

A summary of all methods for editing lists is available at the official Python documentation.

2.2.2.1 Editing list elements

Output:
[6, 8, 10]
[6, 8, 20][6, 8, [21, 22]]

2.2.2.2 Concatenate and append lists

New elements can be attached to the end of the list by the append function:

Output:
['a']
['a', 'b']
Output:
['a', 'b', ['c', 'd', 'e']]
3
Output:
pop() function: ['c', 'd', 'e']
After pop() last element is removed: ['a', 'b']
['a', 'b']
List extended: ['a', 'b', 'c', 'd', 'e', 'f']
Another list extension: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

2.2.2.3 Insert elements

Insert ‘A’ at first position and insert a list at second position

Output:
['A', 'A', ['B', 'C'], 'a', 'b', 'c', 'd', 'e', 'f']
['A', ['B', 'C'], 'A', ['B', 'C'], 'a', 'b', 'c', 'd', 'e', 'f']

2.2.2.4 Remove elements

Remove the element at index 1 an remove the first 5 elements

Output:
['A', ['B', 'C'], 'A', ['B', 'C'], 'a', 'b', 'c', 'd', 'e', 'f']
['A', 'A', ['B', 'C'], 'a', 'b', 'c', 'd', 'e', 'f']
['c', 'd', 'e', 'f']

2.2.3 String to list

When working with text, it is usual that the text is stored in a string variable. Since many text processing tasks are based on word statistics, the string must be split into a list of words. This process is called tokenization and can be realized by using the split() method, as shown in the following code cell:

Output:
['Python', 'is', 'an', 'interpreted,', 'high-level', 'and', 'general-purpose', 'programming', 'language.', "Python's", 'design', 'philosophy', 'emphasizes', 'code', 'readability', 'with', 'its', 'notable', 'use', 'of', 'significant', 'indentation.', 'Its', 'language', 'constructs', 'and', 'object-oriented', 'approach', 'aim', 'to', 'help', 'programmers', 'write', 'clear,', 'logical', 'code', 'for', 'small', 'and', 'large-scale', 'projects']
Output:
['python', 'is', 'an', 'interpreted', 'high-level', 'and', 'general-purpose', 'programming', 'language', "python's", 'design', 'philosophy', 'emphasizes', 'code', 'readability', 'with', 'its', 'notable', 'use', 'of', 'significant', 'indentation', 'its', 'language', 'constructs', 'and', 'object-oriented', 'approach', 'aim', 'to', 'help', 'programmers', 'write', 'clear', 'logical', 'code', 'for', 'small', 'and', 'large-scale', 'projects']
Output:
List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
List type: <class 'list'>
csvString: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
csvString type: <class 'str'>

2.3 Tupels

Tuples are immutable lists. This means that they can not be modified after creation. Their immutable character also protects data against undesired changes. Tuples can be generated similar to lists, their elements are surrounded by parentheses instead of square brackets.

Output:
(2, 4.6, 8, 10, 'a', 'b', 'c', 'a tuple', (1, 2, 3, 4, 5))
<class 'tuple'>
Output:
(2, 4.6, 8, 10, 'a')
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-118-3750f26fc4aa> in <module>
----> 1 tup1[1]=56

TypeError: 'tuple' object does not support item assignment

3 Sets

A set is a collection of distinct objects, which is both unordered and unindexed.

3.1 Generate sets

No object can be contained more than once in a set. Sets are written with curly brackets.

Output:
set()
Output:
hello i am a small text i am a big text
40
{'am', 'big', 'a', 'small', 'i', 'hello', 'text'}
7

3.2 Operations on sets

Copies of sets can be generated by set.copy(). The methods set.add(element) and set.discard(element) can be applied to add and remove single elements into/from a set. For removing all elements of a set set.clear() can be applied.

Output:
{'i', 'am', 'hello', 'text', 'big', 'a', 'small'}
{'i', 'new1', 'am', 'hello', 'text', 'big', 'a', 'small'}
{'a', 'new1', 'am', 'big', 'new2', 'small', 'i', 'hello', 'text'}
{'a', 'am', 'big', 'new2', 'small', 'i', 'hello', 'text'}

3.2.1 Intersection of two sets

All elements, which are contained in the first and in the second set:

Output:
{'am', 'big', 'a', 'small', 'i', 'hello', 'text'}

3.2.2 Union of two sets

All elements, which are contained in the first or in the second set:

Output:
{'am', 'big', 'a', 'new2', 'small', 'i', 'hello', 'text'}

3.2.3 Compare two sets

All elements of the first set, except the ones, which are contained also in the second set.

Output:
{'new2'}

3.2.4 Check the membership

Output:
True
False

3.2.5 Check subset

Output:
False
False
True

3.2.6 Convert set to a list

Set elements can not be accessed by an index. If access to elements is required the set is usually transformed to a list. This can be implemented as follows:

Output:
['a', 'am', 'big', 'new2', 'small', 'i', 'hello', 'text']
hello

3.3 Immutable sets -frozensets

Besides the data type set there exists a second type related to sets — the frozenset. Sets of type frozenset are immutable, it’s content can not be modified after it is created. The attempt to modify a frozenset yields an error.

Output:
frozenset({'a', 'd', 'b', 'c', 'e'})
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-134-ebd710882bd4> in <module>
----> 1 frozSet.add('f')

AttributeError: 'frozenset' object has no attribute 'add'

4. Dictionary

Assume that a set of cars shall be described by their brand, model, fuel type, and year. One option to model this information in Python is to allocate for each car a list, which contains the mentioned parameters as components. Sets of cars could then be modelled as lists of lists.

Output:
['Tesla', 'Model S', 'ELECTRIC', 2020]
['Audi', 'e-Tron', 'ELECTRIC', 2021]
[['Tesla', 'Model S', 'ELECTRIC', 2020], ['Audi', 'e-Tron', 'ELECTRIC', 2021]]

4.1 Generate Dictionary

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and does not allow duplicates. The same information as modelled with lists in the example above, is now modelled with dictionaries. An empty dictionary is defined by curly brackets myDict={} or by myDict=dict().

Output:
{'brand': 'Tesla', 'model': 'Model S', 'fueltype': 'ELECTRIC', 'year': 2020, 'colors': ['black', 'white', 'green']}
dict{'brand': 'Audi', 'model': 'e-Tron', 'fueltype': 'ELECTRIC', 'year': 2021}
dict

4.2 Accessing Dictionary keys and values

The number of key value pairs in a dictionary can be printed by len(dictname)

Output:
5
3
Output:
Keys:
['brand', 'model', 'fueltype', 'year', 'colors']
Values:
['Tesla', 'Model S', 'ELECTRIC', 2020, ['black', 'white', 'green']]
Output:
[('brand', 'Tesla'), ('model', 'Model S'), ('fueltype', 'ELECTRIC'), ('year', 2020), ('colors', ['black', 'white', 'green'])]
Output:
'Model S'

4.3 Modifying Dictionaries

Duplicate (year) values will overwrite existing values, because a dictionary does not allow duplicates values.

Output:
{'brand': 'VW', 'model': 'ID.4', 'fueltype': 'ELECTRIC', 'year': 2021, 'colors': ['yellow', 'black', 'purple']}
dict
Output:
{'brand': 'VW', 'model': 'ID.4', 'fueltype': 'ELECTRIC', 'year': 2021, 'colors': ['yellow', 'black', 'purple']}
5
colors deleted
{'brand': 'VW', 'model': 'ID.4', 'fueltype': 'ELECTRIC', 'year': 2021}
4

4.4 Save dictionaries persistently

For dictionaries, which shall be saved persistently and later be loaded into a program again, the .json file-format is suitable.

4.4.1 Write dictionary to json file

4.4.2 Read dictionary to json file

Output:
{'brand': 'VW', 'model': 'ID.4', 'fueltype': 'ELECTRIC', 'year': 2021}

Data Analyst

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store