Lists, Tuples and Dictionary - Python Programming by Example (2015)

Python Programming by Example (2015)

3. Lists, Tuples and Dictionary

This chapter explains how to work with Python collection.

3.1 Lists

Python provides a list for collection manipulation. We define a list as [].

For illustration, we show you how to use a list in Python program. The program implements

· declaring

· printing

· getting a list length

· adding

· getting a specific item from a list

· sorting

· removing

Write these scripts.

# declare lists

print('----declare lists')

numbers = []

a = [2, 7, 10, 8]

cities = ['Berlin', 'Seattle', 'Tokyo', 'Moscow']

b = [10, 3, 'Apple', 6, 'Strawberry']

c = range(1, 10, 2)

# print(lists

print('----print(lists')

print(a)

for city in cities:

print(city)

print(b)

print(c)

# get length of lists

print('----get length of lists')

print(len(a))

print(len(cities))

# add item into list

print('----add item')

numbers.append(10)

numbers.append(5)

cities.append('London')

for i in numbers:

print(i)

for city in cities:

print(city)

# get specific item

print('----get item')

print(cities[2])

print(a[3])

# sorting

print(a.sort())

# edit item

print('----edit item')

cities[2] = 'new city'

for city in cities:

print(city)

# remove item

print('----remove item')

a.remove(8) # by value

del cities[2] # by index

for city in cities:

print(city)

Save thses scripts into a file, called ch03_01.py.

Run the program.

python3 ch03_01.py

A sample of program output:

p3-1

3.2 Tuples

We can define a tuple using () in Python. A tuple can be append a new item.

For testing, we build a program into a file, called ch03_02.py. Write these scripts.

# declare tuples

a = ()

b = (3, 5, 7)

c = ('Ford', 'BMW', 'Toyota')

d = (3, (5, 'London'), 12)

# print

print(a)

print(b)

print(c)

print(d)

# get length of tuples

print(len(a))

print(len(b))

print(len(c))

print(len(d))

# get item

print(b[2])

print(c[1])

# get index

print(b.index(7))

print(c.index('Toyota'))

Save and run the program.

python3 ch03_02.py

A sample of program output:

p3-2

3.3 Dictionary

We can create an array with key-value or dictionary. Python uses {} to implement key-value array.

For illustration, we create a program, ch03_03.py. Write these scripts.

# declare

a = {}

b = {2: 'Sea', 3: 'River', 8: 'Mountain'}

c = {2: {4: 'abcd', 5: 'hjkl'}, 3: 'vbnm'}

d = dict(name='elena', age=30, roles=('manager', 'consultant'))

# print

print(a)

print(b)

print(c)

print(d)

# keys values

print(b.keys())

print(b.values())

print(b.items())

# add item

a.setdefault(2, 'car')

a.setdefault(5, 'train')

a.setdefault(7, 'plane')

print(a)

# check key

print(3 in b)

print(5 in b)

Save these scripts and run the program.

python3 ch03_03.py

A sample of program output:

p3-3