Python – Working with Lists

 

One of the most common data types in Python is the list. A list is basically an array in other languages, however with a list, you can mix different data types in the same list. You can test this in the interactive shell:

>>> a_list = ['dog', 'cat', 1, 3, 1000]
>>> print(a_list)
['dog', 'cat', 1, 3, 1000]
>>> type(a_list[3])
<class 'int'>
>>> type(a_list[1])
<class 'str'>

Working with Python Lists

After declaring a list, we will need to either add data, delete data or assign data to another variable. In order do accomplish these tasks, we will need to use the append() method to add data, pop() or remove() to delete data, and subset the list to retrieve elements or assign to another variable.

Lists are subsetted by using the brackets ([]), a positional number and / or using a colon (:). Using a colon will allow a subset range.

Note: list elements start at 0 not 1.

>>> a_list = ['dog', 'cat', 'bat']
>>> b_str = a_list[0] # Take the first element and assign it to b_str
>>> b_str
'dog'
>>> type(b_str)
<class 'str'>
>>> a_list[-1] # Take the last element from the list 
'bat'
>>> a_list[-2] # Take the second to last element from the list
'cat'
>>> type(a_list[0]) # Lists can contain ints, strings, dictionaries or other lists
<class 'str'>
>>> type(a_list[-1])
<class 'int'>

Using a range with list elements sometimes is prone to defects in code. The number before the colon is the starting point, and the number after is the position to end minus 1. For example, a_list[1:4] starts at element 1 and ends at element 3, not 4. If you’ve developed in other languages, this will take some time to acclimate to Python’s way of list subscripting.

>>> a_list
['cat', 1, 3, 1000]
>>> a_list[0:3] # Take the first element through the second element
['cat', 1, 3]
>>> a_list[1:-1] # Take the second element through the second to last element
'cat', 1, 3]
Here is an example of a list containing another list and dictionary. Lists containing other lists is common in JSON or RESTful development, so becoming familiar with the syntax is important as you develop more complex or web-enabled applications. We still can call dictionary methods like keys() or values().
>>> b_list = ['this', 'new' 'list']
>>> a_list.append(b_list)
>>> a_list
['cat', 1, 3, 1000, ['this', 'newlist']]

>>> my_dct = {'language': 'Python'}
>>> a_list.append(my_dct)
>>> a_list
['cat', 1, 3, 1000, ['this', 'newlist'], {'language': 'Python'}]
>>> a_list[-1].keys() # We can call dictionary methods  
dict_keys(['language'])
>>> a_list[-1].values()
dict_values(['Python'])

 Simple Merge

Here are some examples of using Python lists by merging two lists into one. This simple example appends the values from second_list onto first_list.

firstList = ['dog', 'cat', 'tiger', 'rhnio']
secondList = ['2 x 18g', '250m swap']

for line in secondList:
   firstList.append(line)

Merge Lists Based on A Condition

The following code merges two lists, but will insert the second list after finding a specific string, in this case a hostname. outerList.pop(0) removes the first element from the list, and then inserts the remaining list into firstList.

firstList = ['dog', 'cat', '2', '500', 'daeo', 'DL580', '8', '128']
secondList = [['dog', '2 x 18g', '250m swap'], ['daeo', '4 x 146g', '16g swap']]

try:
    for outerList in secondList:
        systemName = outerList.pop(0)
        for innerList in outerList:
            indexPos = firstList.index(systemName)
            firstList.insert(indexPos + 1, innerList)
except ValueError as err:
    print('ValueError: {}'.format(err))

 


Docker Containers – Part 1 Installation

Containers in DevOps allows an application to run from any supported environment. An application running in a Container can run in Windows and Linux without any changes to the application. A container is a lightweight piece of software similar in nature to FreeBSD Jails or Linux Containers (LXD). However, a container isn’t like a traditional Operating System. Although Containers are configurable to behave like an OS, this is not the design. Containers are highly configurable, and are able to run just about any application. For example, middle-tier applications, web servers, and in some cases, databases. One of the more popular Containers is Docker, which is the focus of this post, but there are many more.

Docker has a few different offerings. The two most common are Community Edition (CE) and Enterprise Edition (EE). CE is the free and unsupported version whereas EE is a paid model and bundled with support.

Before installing and configuring Docker, we need to understand some key terms.

Images are templates for running a container. For example, building a middle-tier application server, an installation of JBoss, a version of Java and an Oracle driver are required to be part of an image. You can see all of the images on a system by running the docker images command.

Containers are running instances of images. To see the containers, use the command docker ps -a.

Repositories are sets of images with different tags. This is similar to code repositories where you check out different versions of code based upon a tag or version. Omitting the tag will checkout the latest image version. With repos, you can create and share the repo with the world (which is the default behavior) or you can keep the repo private.

Dockerfile is the configuration file used while creating a Docker image.

Installing Docker

Windows

Docker is easy to install no matter which OS is being used. On Windows, use this link to download the stable version of Docker. The installer works like any other – double click it and follow the instructions. Note: .Net version 4.0.3 is required for Docker.

RHEL, CENTos or Fedora Linux

Prerequisites

First, install the following required packages, and then enable the Docker  Yum repository as root or a user with yum sudo privileges.

yum install -y yum-utils device-mapper-persistent-data lvm2

Next, add the Yum Docker repo

yum-config-manager --add-repo  https://download.docker.com/linux/centos/docker-ce.repo

Once these steps are complete, you can use yum to install Docker and service to start the Docker process.

yum install -y docker
service docker start

Ubuntu Linux

Install the prerequisite software, add the gpg key to the system and add the Docker repository. Adding the repository will allow us to use apt-get to install Docker.

apt-get install -y apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

Once the software is installed and the key added to the system, use apt-get to install Docker Community Edition (docker-ce).

apt-get install docker-ce

Linux

No matter which version of Linux,  only the root user is configured to run Docker commands. If other users need permissions, then create a docker group as root, and add the users into the group. The gpasswd command will add the user to the docker group. It takes the username and group as arguments.

groupadd docker
usermod -G docker dockeruser1
service docker restart

After the installation, you can now use the docker command to list images and run containers. In the next post, we will create our own repository and make it publicly available.