Python – lists, dicts, tuples, files, sets, type & class types

This post is the fifth of many that attempts to document everything I have been learning about Python.

Lists

Lists are mutable (objects that can be changed in place) sequences in Python. They are a collection of arbitrary objects ordered by position.

Lists can contain objects of any type and do not have a fixed size.

You can add and remove items to a list by using the append and pop methods of the list object.

>>>
>>> list_of_names = [‘John von Neumann‘, ‘Niels Bohr‘, ‘Nikola Tesla‘]
>>>
>>> # add an item to the list
>>> list_of_names.append(‘John Nash‘)
>>> list_of_names
[‘John von Neumann‘, ‘Niels Bohr‘, ‘Nikola Tesla‘, ‘John Nash‘]
>>>
>>> # remove an item from the list
>>> list_of_names.pop()
John Nash
>>>
>>> list_of_names
[‘John von Neumann‘, ‘Niels Bohr‘, ‘Nikola Tesla‘]
>>>

You cannot use an index that does not exist as a positional offset nor can you assign to it.

>>> # this list has 3 values.
>>> # assigning a value to a 4th offset will
>>> # result in an error
>>> list_of_names[3] = “John Nash
Traceback (most recent call last):
File “”, line 1, in
list_of_names[3] = “John Nash”
IndexError: list assignment index out of range
>>>

You can nest lists arbitrarily.

>>> list_of_names
[‘John von Neumann‘, ‘Niels Bohr‘, ‘Nikola Tesla‘]
>>> a_sub_list = [‘Albert Einstein‘, ‘Alan Turing‘]
>>>
>>> list_of_names.append(a_sub_list)
>>> list_of_names
[‘John von Neumann‘, ‘Niels Bohr‘, ‘Nikola Tesla‘, [‘Albert Einstein‘, ‘Alan Turing‘]]
>>>

Comprehensions.

List Comprehensions are expressions that iterate over any sequence and run a expression over each value in the sequence and return the result in a list

A list comprehension consists of any sequence, a variable that takes on the values of the sequence one at a time and an expression that acts on that variable

>> a_list_comprehension = [x ** 2 for x in [1,2,3]]
>>> a_list_comprehension
[1, 4, 9]
>>>

By enclosing the comprehension in () you can create generators:

>>>
>>> a_generator = (x ** 2 for x in [1,2,3])
>>> next(a_generator)
1
>>> next(a_generator)
4
>>>

You can use this comprehension syntax to generate lists, dictionaries and sets.

Dictionaries

Dictionaries are a mutable type. They are used to map keys to values.

You create a dictionary by wrapping key value pairs in { }

You index a Dictionary type with its key to get to its value.

>>>
>>> testdict = {“languages” : [“Python“, “C#“, “R“], “math” : “Algebra“}
>>> testdict[“languages“]
[‘Python‘, ‘C#‘, ‘R‘]
>>>

When you assign a value to a key that does not exist, that key and value are added to the dictionary, this is unlike the list where adding a value to a index that does not exist results in an error.

>>>
>>> testdict[“field_of_study“] = “HFT
>>> testdict
{‘languages‘: [‘Python‘, ‘C#‘, ‘R‘], ‘field_of_study‘: ‘HFT‘, ‘math‘: ‘Algebra‘}
>>>

Dictionaries are not sequences, so they do not maintain any left to right order.

You can sort dictionaries by getting their keys in a list, sorting the list, using a for loop to move through the list OR you can use the built-in sorted function call that can sort a variety of objects.

>>>
>>> unsorted_dict = {“a” : 1, “b” : 2, “c” : 3}
>>> # no left to right order
>>> unsorted_dict
{‘a‘: 1, ‘c‘: 3, ‘b‘: 2}
>>> sorted(unsorted_dict)
[‘a‘, ‘b‘, ‘c‘]
>>>
>>> keys_in_dict = list(unsorted_dict.keys())
>>> keys_in_dict
[‘a’, ‘c’, ‘b’]
>>> # sort the list
>>> keys_in_dict.sort()
>>> keys_in_dict
[‘a‘, ‘b‘, ‘c‘]
>>>

The in membership expression allows us to check if a key we are trying to retrieve in a dictionary exists. It is an error to index and fetch a non-existent key from a dictionary type.

>>> # Using the ‘in’ membership operator
>>> unsorted_dict
{‘a‘: 1, ‘c‘: 3, ‘b‘: 2}
>>> ‘a’ in unsorted_dict
True
>>>
>>> # Accessing a key that does not exist
>>> unsorted_dict[“test“]
Traceback (most recent call last):
File “”, line 1, in
unsorted_dict[“test”]
KeyError: ‘test’
>>>

You can also call the get method of the dictionary type, this accepts the key name and a default value that will be returned if the key does not exist.

>> unsorted_dict
{‘a‘: 1, ‘c‘: 3, ‘b‘: 2}
>>>
>>> unsorted_dict.get(‘a‘)
1
>>> unsorted_dict.get(‘m‘, 9)
9
>>>

Tuple

A tuple is like a list, in that it is a sequence, but unlike a list, it cannot be changed, it is immutable.

You create a tuple by enclosing a set of values in () separated by commas.

>> wooo_a_tuple = (‘what‘, ‘me‘, ‘pragmatic‘, ‘huh‘)
>>>

Files

This type represents external files. Unlike other types, you cannot use a literal to create it, rather, you need to call the built-in open function by passing in the external file name and a access type as parameters.

>>>
>>> file_name = open(‘testfile.txt‘,’w‘)
>>> file_name.write(“this is a test string“)
21
>>> file_name.close()
>>> file_name_to_read = open(‘testfile.txt‘, ‘r‘).read()
>>> file_name_to_read
this is a test string
>>>

Sets

Sets are collections of unordered, unique immutable objects. You can think of them as valueless dictionaries. They are created using {}

>> title_town = {“Celtics“, “Patriots“, “Red Sox“, “Bruins“}
>>>

Decimals and Fractions

Decimals and Fractions are the 2 new types added, they are not part of the core built-in types and have to be imported.

>>>
>>> from fractions import Fraction
>>> var = Fraction(3, 4)
>>> var
Fraction(3, 4)
>>> var1 = Fraction(1, 4)
>>> var1
Fraction(1, 4)
>>> var + var1
Fraction(1, 1)
>>>
>>> from decimal import Decimal
>>> dec1 = Decimal(“1.0“)
>>> dec2 = Decimal(“33.3“)
>>> dec1 + dec2
Decimal(‘34.3‘)
>>>

Bool

The Boolean type is essentially a numeric type, it represents values 1 and 0, prints them out as True and False.

>> bool_var = True
>>> # it really is an integer
>>> bool_var + 1
2
>>>

Type

The type built in function returns the type of the object being passed to it.

>>> type(bool_var)
>>> type(unsorted_dict)
>>>

Class

The class keyword allows you to declare your own types that model real world entities.

>>> class Author(object):
def __init__(self, first, last):
self.first = first
self.last = last
def print_name(self):
print(self.first, self.last)

>>> wealth_of_nations = Author(“Adam“, “Smith“)
>>> wealth_of_nations.print_name()
Adam Smith
>>>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s