Statements in Python

These are my notes and worked examples on statements in python.

Writing Lists

In Python, a variable must be initialized before it can be used. This is usually done in the statement that uses it. 

More than one variable can be initialized  with the same value using a single statement. 

A = b = d = e = 10

More than one variable can also be initialized to different values using commas in a statement.

A, b, c, = 15, 25, 35

Unlike regular variables, which can only store a single item of data, Python can use a list which can store multiple items of data. The data is stored sequentially in list elements that are index numbered starting at zero. The first value is stored in element zero and goes up from there.

A list is created much like any other variable, but it is initialized by assigning values as a comma-separated list between square brackets.

num=[0,1,2,3,4,5]

An individual list element can be referenced using the list name followed by square brackets containing that element’s index number. This means that num[1] references the second element in the example above, since the first element starts at zero.

Lists can have more than one index to represent multiple dimensions, rather than the single dimension of a regular list. Multi-dimensional lists of three indices and more are uncommon but two-dimensional lists are useful to store grid-based information such as [x,y] coordinates.

A list of string values can even be considered to be a multi-dimensional list, as each is itself a list of characters. Each character can be referenced by its index number within its particular string.

 

quarter=[‘January’, ‘February’, ‘March’]

print(‘First Month:’, quarter[0])

print(‘Second Month:’, quarter[1])

print(‘Third Month:’, quarter[2])

coordinates=[ [1,2,3] , [4,5,6] ]

print(‘\nTop Left 0,0:’, coordinates[0][0] )

print(‘Bottom Right 1,2:’, coordinates[1][2] )

print(‘\nSecond Month First Letter:’, quarter[1][0] )

 

String indices may also be negative numbers. To start counting from the right where -1 references the last letter.

 

Manipulating Lists

List variables can contain multiple items of data. They are widely used in Python and have a number of methods and options.



list.append(x)

Adds item x to the end of the list

list.extend(L)

Adds all items in list L to the end of the list

list.insert(i,x)

Inserts item x at index position i

list.remove(x)

Removes first item x from the list

list.pop(i)

Removes item at index i and returns it 

list.index(x)

Returns the index in the list of first item x

list.count(x)

Returns the number of times x appears in list

list.sort()

Sort all list items, in place

list.reverse()

Reverse all list items, in place

 

Python also has a useful len(L) function that returns the length of the list L as the total number of elements it contains. Like the index() and count() methods, the returned value is numeric so cannot be directly concatenated to a text string for output.

String representation of numeric values can be produced by Python’s str(n) function for concatenation to other strings, which returns a string version of the numeric n value. A string representation of an entire list can be returned by the str(L) function for concatenation to other strings. Remember that the original version remains unchanged as the returned versions are merely copies of the original version.

Individual list elements can be deleted by specifying their index number to the Python del(i) function. This can remove a single element at a specified i index position, or a slice of elements can be removed using slice notation i1:i2 to specify the index number of the first and last element. In this case, i1 is the index number of the first element to be removed and all elements up to, but not including, the element at the i2 index number will be removed.

 

basket=['Apple', 'Bun', 'Cola']

crate=['Egg', 'Fig', 'Grape']




print('Basket List:', basket)

print('Basket Elements:', len(basket))




basket.append('Damson')

print('Appended:', basket)

print('Last Item Removed:', basket.pop())

print('Basket List:', basket)




basket.extend(crate)

print('Extended:', basket)

del basket[1]

print('Item Removed:', basket)

del basket[1:3]

print('Slice Removed:', basket)

 

The last index number in the slice denotes at what point to stop removing elements, but the element at that position does not get removed.

 

Restricting Lists

For a tuple, the values in a regular list can be changed as the program proceeds, but a list can be created with fixed immutable values that cannot be changed by the program. A restrictive immutable Python list is known as a tuple and is created by assigning values as a comma-separated list between parentheses in a process known as tuple packing.

colors-tuple=(‘Red’, ‘Green’, ‘Red’, ‘Blue’, ‘Red’)

An individual tuple element can be referenced using the tuple name followed by square brackets containing that element’s index number. Usefully, all values stored inside a tuple can be assigned to individual variables in a process known as sequence unpacking.

A,b,c,d,e = colors-tuple

For a set, the values in a regular list can be repeated in its elements, as in the tuple above, but a list of unique values can be created where duplication is not allowed. A restrictive Python list of unique values is known as a set and is created by assigning values as a comma-separated list between curly brackets.

phonetic-set={‘Alpha’, ‘Bravo’, ‘Charlie’)

Individual set elements cannot be referenced using the set name followed by square brackets containing an index number, but instead sets have methods that can be dot-suffixed to the set  name for manipulation and comparison. 



set.add(x)

Adds item x to the set

set.update(x,y,z)

Adds multiple items to the set

set.copy()

Returns a copy of the set

set.pop()

Removes one random item from the set

set.discard(x)

Removes item x if found in the set

set1.intersection(set2)

Returns items that appear in both sets

set1.difference(set2)

Returns items in set1 but not in set2

  



zoo=('Kangaroo', 'Leopard', 'Moose',)

print('Tuple:', zoo, '\tLength:', len(zoo))

print(type(zoo))




bag={'Red', 'Green', 'Blue'}

bag.add('Yellow')

print('\nSet:', bag, '\tLength', len(bag))

print(type(bag))




print('\nIs Green in bag Set?:', 'Green' in bag)

print('Is Orange in bag Set?:', 'Orange' in bag)




box={'Red', 'Purple', 'Yellow'}

print('\nSet:', box, '\t\tLength', len(box))

print('Common to both Sets:', bag.intersection(box))



In Python programming a dictionary is a data container that can store multiple items of data as a list of key:value pairs. Unlike regular list container values, which are referenced by their index number, values stored in dictionaries are referenced by their associated key. The key must be unique within that dictionary, and is typically a string name although numbers may be used.

Creating a dictionary is simply a matter of assigning the key:value pairs as a comma-separated list between curly brackets to a name of your choice. Strings must be enclosed within quotes, as usual, and a : colon character must come between the key and its associated value.

A key:value pair can be deleted from a dictionary by specifying the dictionary name and the pair’s key to the del keyword. Conversely, a key:value pair can be added to a dictionary by assigning a value to the dictionary’s name and a new key.

Python dictionaries have a keys() method that can be dot-suffixed to the dictionary name to return a list, in random order, of all the keys in that dictionary. If you prefer the keys to be sorted into alphanumeric order, simply enclose the statement within the parentheses of the Python sorted() function.

A dictionary can be searched to see if it contains a particular key with the Python in operator, using the syntax key “in” dictionary. The search will return a boolean True value when the key is found in the specified dictionary, otherwise it will return false.

Two dictionaries can be merged into one single dictionary using the | merge operator, where dict3=dict1 | dict2. Alternatively, a dictionary can be merged with a second dictionary using the |= update operator, where dict1 |= dict2.

Dictionaries are the final type of data container available in Python. Here are the types again:



Variable

A single value

List

Multiple values in an ordered index

Tuple

Multiple fixed values in a sequence

Set

Unique values in an unordered collection

Dictionary

Multiple unordered key:value pairs

 

user_sys={'name': 'Bob', 'sys': 'Win'}

user_lang={'name': 'Bob', 'lang': 'Python'}




dict=user_sys|user_lang

print('\nDictionary:', dict)




print('\nLanguage:', dict['lang'])




print('\nKeys:', dict.keys())




del dict['name']

dict['user']='Tom'

print('\nDictionary:', dict)




print('\nIs There A Name Key?:', 'name' in dict)

 

Notice the quotes must be preceded by a backslash character within a string to prevent the string being prematurely terminated.