Python Primer part 1 — Data types

Marius Safta
Cluj School of AI
Published in
5 min readApr 19, 2019

Hello World,

This is part one of a quick reference about Python. The purpose is not to act as or replace a full Python course, but to be a fast get up to speed on Python for people that have some developer experience.

At the end of this series there will be links to other resources, including full courses for those looking for a more in-depth look.

The Basics

Python uses dynamic typing, meaning variables can be reassigned to other data types. This comes with pros and cons… The advantage is that it’s easier to work with which translates to faster development time. But it also leaves the door open for unexpected errors which might be difficult to debug and forces you to constantly be aware of type.

As expected, Python supports most common types of data:

  • Integer
  • Float
  • Boolean
  • String
  • List
  • Dictionary
  • Set
  • Tuple

Naming conventions dictate lower_with_underscore for variables, functions and modules and CapWords for class names. More about Python naming conventions in Google’s Python style guide.

Strings

Everything in Python is 0 indexed.

Python comes with common string methods:

upper makes all letters in a string uppercase

s = “Hello World”print(s.upper())>> HELLO WORLD

lower() makes all letters in a string lowercase

s = “Hello WORLD”print(s.lower())>> hello world

The split() method — splits the string after the parameter string and return a list of items

s = “Hello World it is me!”print(s.split(“ ”))>> [“hello”, “World”, “it”, “is”, “me”]s = “Hello World it is me!”print(s.split(“o”))>> [“hell”, “ W”, “rld it is me”]

The length of a string is returned by the len method which can be used for lists, dictionaries and sets as well, so it’s not a string specific method.

s = “Hello World”print(len(s))>> 11

Strings can be formatted with dynamic information inside the print statement with the format method.

my_steps = 10000print(“I have walked {} steps today”.format(my_steps))>> I have walked 10000 steps today

String slicing is done with “:”. This returns a portion of the string. The slicing operation doesn’t affect the original string, it just returns a portion of it.

Everything after the first two characters:

s = “Hello World”print(s[2:])>> llo World

Everything until the fourth character:

s = “Hello World”print(s[:3])>> Hel

All characters in an interval, from the second until the fifth character:

s = “Hello World”print(s[1:4])>> ell

Slicing can be done from the end of the string using negative indexes. The -1 index returns the last character in the string.

print(s[-1])>> d

Concatenation is done via the + operator.

first_string = “Hello”second_string = “World”print (first_string + second_string)>> HelloWorld

Strings are immutable, so you can’t change individual characters. The below example will prompt an error.

s = “Hello World”s[2] = “a”>> ERROR

Lists

A List can contain items of different data types. The list below is valid.

my_list = [1, “two”, 3]

Indexing works the same as with strings (0 indexed):

print(my_list[1])>> two

The len function returns how many elements are in the list

print(len(my_list))>> 3

Slicing works the same as for strings.

print(my_list[1:])>> [“two”, 3]print(my_list[:2])>> [1, “two”]

To create a list with a repeating element use the * operator.

initial_list = [0] * 5print(initial_list)>> [0, 0, 0, 0, 0]

To add a new item to the list, use the append method.

my_list = [1, 2, 3]my_list.append(“four”)print(my_list)>> [1, 2, 3, “four”]

To extract the last element in the list, use the pop method.

element = my_list.pop()print(element)>> four

Specifying an index will return the element at that position in the list.

element = my_list.pop(0)print(element)>> 1

Every time pop is used, the list loses that element. We have only two elements remaining in the list.

print(my_list)>> [2, 3]

The sort method sorts the elements within the list. Just as pop, the sort method changes the list.

my_list = [1, 5, 8, 3, 9, 0]my_list.sort()print(my_list)>> [0, 1, 3, 5, 8 , 9]

As the name suggests, the reverse method reverses the list element order.

my_list = [1, 5, 8, 3, 9, 0]my_list.reverse()print(my_list)>> [0, 9, 3, 8, 5, 1]

Dictionaries

A dictionary is a key-value data structure, where a value is stored at a location which is accessible by calling the associated key.

my_info = {}my_info[‘name’] = “John Doe”my_info[‘age’] = 30print(my_info)>> {‘name’: “John Doe”, ‘age’: 30}print(my_info[‘name’])>> John Doeprint(my_info[‘age’])>> 30

Dictionary can “house” any data type in a key, for example a list.

my_info[‘pets’] = [“dog”, “cat”, “parrot”]

All data types in a dictionary retain their properties and methods. We use the upper() method on the string at index 1 in the list.

print(my_info[‘pets’][1].upper())>> CAT

Sets

A Set is an unordered collection of unique elements.

To initialize a set we use set() and add elements to it with the add() method.

my_set = set()my_set.add(1)my_set.add(2)print(my_set)>> {1, 2}

We can easily transform a list into a set. The process will eliminate any duplicate elements.

my_list = [1, 1, 1, 2, 2, 3, 4, 5, 6, 6]my_set = set(my_list)print(my_set)>> {1, 2, 3, 4, 5, 6}

Tuples

Tuples are very similar to lists, with one key distinction: they are immutable, so they can’t be changed. They are used to keep data that shouldn’t change, such as days in the week.

my_tuple = (1, 2, “three”)Indexing, slicing and length work the same way as for lists.print(len(my_tuple))>> 3print(my_tuple[0])>> 1print(my_tuple[:2])>> (1, 2)

Being immutable, any change attempt will output an error.

my_tuple[0] = 9>> ERROR

All above examples are in a Jupyter notebook available on Github. You will only be able to see a read-only version.

To run the notebook, download the file and open it with Jupyter Notebook on your local machine. If you’ve followed a previous post, open Jupyter Notebook from Anaconda Navigator. Once the notebook is open, click on a code cell and then SHIFT+ENTER to run the code in the cell and see the output. Alternatively, press the Run button in the upper menu.

Running a cell inside Jupyter Notebook

Conclusion

This article was a review of Python data types and their most common methods. In part II of this Python Primer we’ll see how to work with these data types in a “pythonic” way.

Your opinions, feedback or (constructive) criticism are welcomed in discussions below or at @mariussafta

Join our Facebook and Meetup groups and keep an eye out for discussions and future meetups.

--

--