Chapter 8: Data Structures

Introduction

There are four built-in data structures in Python:

1. list
2. tuple
3. dictionary
4. set

List

Once you have created a list, you can add, remove or search for items in the list.

Quick Introduction To Object And Classes

A list is an example of usage of objects and classes.

using_list.py

# Filename: using_list.py

# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana', 'orange']

# single quotation and double quotation in print funcion is OK
print('I hava', len(shoplist), 'items to purchase')
print("I hava", len(shoplist), "items to purchase")

print('These items are:', end=' ')

for item in shoplist:
    print(item, end='|')

print() # new line

print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now:', shoplist)

print('\nI will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)

print('\nThe first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)

using_list.py の実行結果は:

[wtopia py.byte]$ python3 using_list.py
I hava 5 items to purchase
I hava 5 items to purchase
These items are: apple|mango|carrot|banana|orange|

I also have to buy rice.
My shopping list is now: ['apple', 'mango', 'carrot', 'banana', 'orange', 'rice']

I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'orange', 'rice']

The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'orange', 'rice']

if you want to know all the methods defined by the list object, see help(list) for details:

>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new list
 |  list(sequence) -> new list initialized from sequence's items
 |
 |  Methods defined here:
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 ... (省略)

Tuple

using_tuple.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Filename: using_tuple.py

zoo = ('python', 'elephant', 'penguin')
zoo = 'python', 'elephant', 'penguin' # () がなくても okay
print('Number of animals in the zoo is', len(zoo))

new_zoo = ('monkey', 'camel', zoo,)
print('Number of animals in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)

print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))

print(1, 2, 3) # print three numbers
print( (1, 2, 3) ) # print a tuple

myempty = () # tuple with 0 items
print('Number of myempty is', len(myempty))

singleton=(2,) # tuple with 1 items
print('Number of singleton is', len(singleton))

using_tuple.py の実行結果は:

[wtopia py.byte]$ python3 using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5
1 2 3
(1, 2, 3)
Number of myempty is 0
Number of singleton is 1

Dictionary

Pairs of keys and values are specified in a dictionary by using the notation:

d = {key1 : value1, key2 : value2}

Remember that key-value pairs in a dictionary are not ordered in any manner. If you want a particular order, then you will have to sort them yourself before using it.

using_dict.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Filename: using_dict.py

# 'ab' is short for 'a'ddress 'b'ook

ab = {
    'wtopia' : 'wtopia@live.jp',
    'larry' : 'larry@live.com',
    'kelly' : 'kelly@gmail.com',
    'hooper' : 'hooper@yahoo.co.jp'
    }

print("wtopia's E-Mail address is", ab['wtopia'])

# Deleting a key-value pair
del ab['larry']

print( '\nThere are {0} contacts in the address-book\n'.format(len(ab)) )

for name, address in ab.items():
    print('Contact {0} at {1}'.format(name, address))

# Adding a key-value pair
ab['yangyang'] = 'yy@qq.com'

if 'yangyang' in ab:
    print("\nyangyang's E-Mail address is", ab['yangyang'])

using_dict.py の実行結果は:

[wtopia py.byte]$ python3 using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals

[wtopia py.byte]$ python3 using_dict.py
wtopia's E-Mail address is wtopia@live.jp

There are 3 contacts in the address-book

Contact wtopia at wtopia@live.jp
Contact kelly at kelly@gmail.com
Contact hooper at hooper@yahoo.co.jp

yangyang's E-Mail address is yy@qq.com

Sequences

The examples of sequences are:

1. lists
2. tuples
3. strings

seq.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Filename: seq.py

shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'wtopia'

# Indexing or 'Subscription' operation
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])

print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
print('Item -3 is', shoplist[-3])
print('Item -4 is', shoplist[-4])

print('Character 0 is', name[0])
print('Character -1 is', name[-1])

# Slicing on a list
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])

# Slicing on a string
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])

seq.py の実行結果は:

[wtopia py.byte]$ python3 seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item -3 is mango
Item -4 is apple
Character 0 is w
Character -1 is a
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is to
characters 2 to end is opia
characters 1 to -1 is topi
characters start to end is wtopia

We can also provide a third argument for the slice, which is the step for the slicing (by default, the step size is 1):

>>> shoplist
['apple', 'mango', 'carrot', 'banana']
>>> shoplist[1:3:1]
['mango', 'carrot']
>>> shoplist[1:3:2]
['mango']
>>> shoplist[::2]
['apple', 'carrot']
>>> shoplist[::3]
['apple', 'banana']
>>> shoplist[::-1]
['banana', 'carrot', 'mango', 'apple']
>>> shoplist[::-2]
['banana', 'mango']

Set

Using sets, you can test for membership, whether it is a subset of another set, find the intersection between two sets, and so on:

>>> bri = set(['brazil', 'russia', 'india'])
>>> bri
{'brazil', 'india', 'russia'}
>>> 'india' in bri
'india' in bri
True
>>> 'china' in bri
False
>>> bric = bri.copy()
>>> bric
{'brazil', 'india', 'russia'}
>>> bric.add('china')
>>> bric
{'brazil', 'china', 'india', 'russia'}
>>> bric.issuperset(bri)
True
>>> bri.issuperset(bric)
False
>>> bri.remove('russia')
>>> bri
{'brazil', 'india'}
>>> bric
{'brazil', 'china', 'india', 'russia'}
>>> bri & bric
{'brazil', 'india'}
>>> bri.intersection(bric)
{'brazil', 'india'}

References

reference.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# Filename: reference.py

print('Simple Assignmet')
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object

del shoplist[0] # I purchased the first item, so I remove it from the list

print('shoplist is', shoplist)
print('mylist is', mylist)
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object

print('Copy by making a full slice')
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item

print('shoplist is', shoplist)
print('mylist is', mylist)
#notice that now the two lists are different

reference.py の実行結果は:

[wtopia py.byte]$ python3 reference.py
Simple Assignmet
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

More About Strings

Strings are also objects and have methods which do everything from checking part of a string to stripping spaces.

For a complete list of such methods, see:

help(str)

str_methods.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Filename: str_methods.py

name = 'wtopia' # This is a string object

if name.startswith('wt'):
    print('Yes, the string starts with "wt"')

if 'a' in name:
    print('Yes, it contains the string "a"')

if name.find('ia') != -1:
    print('Yes, it contains the string "ia"')

delimiter1 = '_*_'
delimiter2 = '--'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter1.join(mylist))
print(delimiter2.join(mylist))

str_methods.py の実行結果は:

[wtopia py.byte]$ python3 str_methods.py
Yes, the string starts with "wt"
Yes, it contains the string "a"
Yes, it contains the string "ia"
Brazil_*_Russia_*_India_*_China
Brazil--Russia--India--China

The find method is used to do find the position of the given string in the string or returns -1 if it is not successful to find the substring.

Table Of Contents

Previous topic

Chapter 7: Modules

Next topic

Chapter 9: Problem Solving