Slicing

Objectives

a Slicing is a useful technique to operate on all sequenz data types. Helpful examples are given in this station.

Instructions

Tasks:
  1. Create a tuple or a list with the following sentence and store each word as a value: “Simple is better than complex”
  2. Return the last value of the tuple or list.
  3. Create a dictionary with ten concept pairs <first language> – <second language>.
  4. Print the content of the dictionare in order.
  5. Construct a data structure which stores the position of a chess game.
  6. Return the position as ASCII art.

What is slicing?

It is the selection of a subset of a sequence of values. This works with strings, tuples and lists alike.

Cut part range from - to:

s = "Big Bug Bunny"
part = s[8:10]
print(s, part)

Cut the last part:

s = "Big Bug Bunny"
part = s[-1:]
print(s, part)

Cut first element:

s = "Big Bug Bunny"
part = s[0]
print(s, part)

Cut all elements:

s = "Big Bug Bunny"
part = s[:] # same as s without braces
print(s, part)

Nested Views

What applies to the strings, can also be applied to tuples and lists. If the element is a character string, it can also partly cut again:

t1 = ('The', 'quick', 'brown fox', 'jumps', 'over', 'the', 'lazy', 'dog')
t2 = t1[2][3:8]
print(t2)

Dictionaries and slicing

For the data type * dictionary * there is no slicing operator! Various methods returns a list as a result. If the result is a list, slicing is possible again.

# create a dictionary...

mushrooms = {} # empty dictionary
mushrooms['cep'] = ['eatable x times', "mixed forest", "Boletus edulis"]
mushrooms['fly amanita'] = ["eatable once", "coniferous forest", "Amanita muscaria"]
mushrooms['bay bolete'] = ["eatable x times", "mixed forest", "Boletus badius"]
mushrooms['Coprinus'] = ['eatable x times', "meadow", "Coprinus"]

# print the content:

print('''Pretty print dictionary of mushrooms:\n ''')

for i in mushrooms.keys():
    print("""kind = {}, eatable = {}, be found = {}; """.format(i,
                                                                mushrooms[i][0],
                                                                mushrooms[i][1]))