Share this page : facebooktwitterlinkedinmailfacebooktwitterlinkedinmail



Lists, strings and tuples are ordered sequences of objects. Unlike strings that contain only characters, list and tuples can contain any type of objects. Lists and tuples are like arrays.

Tuples like strings are immutable, but Lists are mutables so they can be extended or reduced at will. Sets are mutable unordered sequence of unique elements whereas frozensets are immutable sets. If you don’t care about order, set will be a better choice over list.

Lists are enclosed in brackets:

l = [1, 2, "a"]

Convert other type of data to lists with list(), split():


['c', 'a', 't']

>>>a_tuple=('ready','fire', 'aim')
['ready', 'fire', 'aim']

>>> birthday = '1/6/1952'
>>> birthday.split('/')
['1', '6', '1952']

If you specify a offset before the beginning or after the end, you will get an exception (error).

>>> marxes = ['Groucho', 'Chico', 'Harpo']
>>> marxes[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

Lists can contain elements of different types, including other lists, as illustrated here:

>> small_birds = [‘hummingbird’, ‘finch’] >>> extinct_birds = [‘dodo’, ‘passenger pigeon’, ‘Norwegian Blue’] >>> carol_birds = [3, ‘French hens’, 2, ‘turtledoves’] >>> all_birds = [small_birds, extinct_birds, ‘macaw’, carol_birds]

So what does all_birds, a list of lists, look like?

>> all_birds
[[‘hummingbird’, ‘finch’], [‘dodo’, ‘passenger pigeon’, ‘Norwegian Blue’], ‘macaw’,
[3, ‘French hens’, 2, ‘turtledoves’]]

If we want the first item of extinct_birds, we can extract it from all_birds by specifying two indexes:

>> all_birds[1][0] ‘dodo

Get a Slice to Extract Items by Offset Range

You can extract a subsequence of a list by using a slice:

>> marxes = [‘Groucho’, ‘Chico,’ ‘Harpo’] >>> marxes[0:2] [‘Groucho’, ‘Chico’]



Tuples are enclosed in parentheses:

t = (1, 2, "a")

Tuples are faster and consume less memory.

Dictionaries are built with curly brackets or dict() builtin function:

If you need some words paired with definition (explanation), then you need dictionary.  you specify a unique key to associate with each value.  When you want to query value (definition , explanation) from dictionary by key, you need to use brackets instead of curly brackets : dictionary[key].

d = {"book":"make people wise", "drug":"kills people"}

To query  the value of book:



make people wise


To make a dictionary by dict() and zip():

>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print dictionary
{'a': 1, 'b': 2, 'c': 3}

A set is like a dictionary with its values thrown away, leaving only the keys in curly brackets. As with a dictionary, each key must be unique. You use a set when you only want to know that something exists.

Sets can be made using the set() builtin function.

>>> set( 'letters' )
{'l', 'e', 't', 'r', 's'}

Notice that the set contains only one ‘e’ or ‘t’, even though ‘letters’ contained two of each.

The union of two sets will contain only one of each key.


Make a set from a list:

>> set( ['Dasher', 'Dancer', 'Prancer', 'Mason-Dixon'] )
{'Dancer', 'Dasher', 'Prancer', 'Mason-Dixon'}

This time, a set from a tuple:

>>> set( ('Ummagumma', 'Echoes', 'Atom Heart Mother') )
{'Ummagumma', 'Atom Heart Mother', 'Echoes'}

When you give set() a dictionary, it uses only the keys:

>>> set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} )
{'apple', 'cherry', 'orange'}

Test for value by using in

This is the most common use of a set. We’ll make a dictionary called drinks. Each key is the name of a mixed drink, and the corresponding value is a set of its ingredients:

>> drinks = {
... 'martini': {'vodka', 'vermouth'},
... 'black russian': {'vodka', 'kahlua'},
... 'white russian': {'cream', 'kahlua', 'vodka'},
... 'manhattan': {'rye', 'vermouth', 'bitters'},
... 'screwdriver': {'orange juice', 'vodka'}
... }

Even though both are enclosed by curly braces ({ and }), a set is just a sequence of values, and a dictionary is one or more key : value pairs.

Which drinks contain vodka? (Note that I’m previewing the use of for, if, and, and or from the next chapter for these tests.)

>>> for name, contents in drinks.items():
... if 'vodka' in contents:
... print(name)
black russian
white russian

One but not another

We want something with vodka but are lactose intolerant, and think vermouth tastes like kerosene:

>>> for name, contents in drinks.items():
... if 'vodka' in contents and not ('vermouth' in contents or
... 'cream' in contents):
... print(name)

black russian

One or another

Suppose that you want to find any drink that has orange juice or vermouth? We’ll use the set intersection operator, which is an ampersand (&):

>>> for name, contents in drinks.items():
... if contents & {'vermouth', 'orange juice'}:
... print(name)

we wanted vodka but neither cream nor vermouth:

>>> for name, contents in drinks.items():
... if 'vodka' in contents and not contents & {'vermouth', 'cream'}:
... print(name)
black russian
Test the Relation of sets

You get the intersection (members common to both sets) with the special punctuation symbol & or the set intersection() function, as demonstrated here:

>>> a & b
>>> a.intersection(b)

To get the union (members of either set) by using | or the set union() function:

>>> a | b
{1, 2, 3}
>>> a.union(b)
{1, 2, 3}

The difference (members of the first set but not the second) is obtained by using the character – or difference():

>>> a - b
>>> a.difference(b)

Exclusive or

The exclusive or (items in one set or the other, but not both) uses ^ or symmetric_difference():

>>> a ^ b
{1, 3}
>>> a.symmetric_difference(b)
{1, 3}

whether one set is a subset of another (all members of the first set are also in the second set) by using <= or issubset():

>>> a <= b
>>> a.issubset(b)

Following is always true:

>>> a <= a
>>> a.issubset(a)

To be a proper subset, the second set needs to have all the members of the first and more. Calculate it by using <

>>> a < b
>>> a < a

A superset is the opposite of a subset (all members of the second set are also members of the first). This uses >= or issuperset():

>>> a >= b
>>> a.issuperset(b)

Any set is a superset of itself:

>>> a >= a
>>> a.issuperset(a)

A proper superset (the first set has all members of the second, and more) by using >:

>>> a > b

you make a list by using square brackets ([]), a tuple by using commas, and a dictionary by using curly brackets ({}). In each case, you access a single element with square brackets:

>>> marx_list = ['Groucho', 'Chico', 'Harpo']
>>> marx_tuple = 'Groucho', 'Chico', 'Harpo'
>>> marx_dict = {'Groucho': 'banjo', 'Chico': 'piano', 'Harpo': 'harp'}
>>> marx_list[2]
>>> marx_tuple[2]
>>> marx_dict['Harpo']
Combine the built-in data structures

You can combine these built-in data structures into bigger, more complex structures of your own. Let’s start with three different lists:

>>> marxes = ['Groucho', 'Chico', 'Harpo']
>>> pythons = ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin']
>>> stooges = ['Moe', 'Curly', 'Larry']

We can make a tuple that contains each list as an element by simple separate them by comma:

>>> tuple_of_lists = marxes, pythons, stooges
>>> tuple_of_lists
(['Groucho', 'Chico', 'Harpo'],
['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin'],
['Moe', 'Curly', 'Larry'])

And, we can make a list that contains the three lists:

>>> list_of_lists = [marxes, pythons, stooges]
>>> list_of_lists
[['Groucho', 'Chico', 'Harpo'],
['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin'],
['Moe', 'Curly', 'Larry']]

Finally, let’s create a dictionary of lists.

>>> dict_of_lists = {'Marxes': marxes, 'Pythons': pythons, 'Stooges': stooges}
>>> dict_of_lists
{'Stooges': ['Moe', 'Curly', 'Larry'],
'Marxes': ['Groucho', 'Chico', 'Harpo'],
'Pythons': ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin']}
None in function


This seems like a subtle distinction, but it’s important in Python. You’ll need None to distinguish a missing value from an empty value. Remember that zero-valued integers or floats, empty strings (”), lists ([]), tuples ((,)), dictionaries ({}), and sets(set()) are all False, but are not equal to None.

>>> def is_none(thing):
... if thing is None:
... print("It's None")
... elif thing:
... print("It's True")
... else:
... print("It's False")
>>> is_none(None)
It's None
>>> is_none(True)
It's True
>>> is_none(False)
It's False
>>> is_none(0)
It's False
>>> is_none(0.0)
It's False
>>> is_none(())
It's False
>>> is_none([])
It's False
>>> is_none({})
It's False
>>> is_none(set())
It's False


Python file

To call the script there are two ways:

1.  If your python is in directory /usr/local/bin/python3.6. Save the file in a folder (/root/, which include code:
import subprocess'date')
Then issue command:

 /usr/local/bin/python3.6  /root/ 

The result will be :

Wed  7 Dec 2016 10:56:40 AEDT

2. Or you can create a file  /root/ which include:

import subprocess'date')
chmod +x /root/