﻿ ﻿Making lists - Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

4. Making lists

This chapter demonstrates how to create code to store data in lists and how to retrieve data from lists.

Writing lists

Changing lists

Fixing lists

Setting lists

Naming elements

Summary

Writing lists

Some programming languages allow variables to be declared with no initial value, but in Python programming a variable must be assigned an initial value (initialized) in the statement that declares it – otherwise the interpreter will report a “not defined” error.

Multiple variables can be initialized with a common value in a single statement using a sequence of = assignments. For example, to simultaneously assign a common value to three variables:

a = b = c = 10

Alternatively, multiple variables can be initialized with differing values in a single statement using comma separators. For example, to simultaneously assign different values to three variables:

a , b , c = 1 , 2 , 3

Unlike a regular variable, which can only store a single item of data, an array variable can store multiple items of data. In Python these are known as “list” variables. The data is stored sequentially in list “elements” that are index numbered starting at zero. So the first value is stored in element zero, the second value is stored in element one, and so on. An array list is created much like any other variable but is initialized by assigning values as a comma-separated list between square brackets. For example, creating a list named “nums” like this:

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

A single list element can be referenced using the list name followed by square brackets containing that element’s index number. This means that nums[1] references the second element in the example above – not the first element. As element numbering starts at zero its first element is referenced with nums[0].

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 string is itself a list of characters. So each character can be referenced by its index number within its particular string.

list.py

Start a new program by initializing a list of three elements containing string values

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

Next, add statements to individually display the value contained in each list element

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

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

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

Add a statement to create a multi-dimensional list of two elements, which themselves are lists that each have three elements containing integer values

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

Now, add statements to display the values contained in two specific inner list elements

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

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

Finally, add a statement to display just one character of a string value

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

Save then run the program – to see the list element values get displayed

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

Loop structures, which are introduced later in this chapter, are often used to iterate through list elements.

Changing lists

List variables, which can contain multiple items of data, are widely used in Python programming and have various function “methods” that can be “dot-suffixed” to the list name for manipulation:

 List Method: Description: 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 position i and returns it list.index(x) Returns the index position in the list of first item x list.count(x) Returns the number of times x appears in the list list.sort() Sort all list items, in place list.reverse() Reverse all list items, in place

For lists that contain both numerical and string values the sort() method returns the list elements sorted first numerically then alphabetically – for example as 1,2,3,A,B,C.

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, however, be produced by Python’s str(n) function for concatenation to other strings, which returns a string version of the numeric n value. Similarly, a string representation of an entire list can be returned by the str(L) function for concatenation to other strings. In both cases 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 the list name and index number after the Python del keyword. This can remove one element at a specified i index position, or a “slice” of elements 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.

Python also has an int(s) function that returns a numeric version of the string s value.

pop.py

Start a new program by initializing two lists of three elements each containing string values

basket = [ ‘Apple’ , ‘Bun’ , ‘Cola’ ]

crate = [ ‘Egg’ , ‘Fig’ , ‘Grape’ ]

Next, add statements to display the contents of the first list’s elements and its length

Now, add statements to add an element and display all list elements, then remove the final element and display all list elements once more

print( ‘Last Item Removed:’ , basket.pop() )

Finally, add statements to add all elements of the second list to the first list and display all the first list elements, then remove elements and display the first list again

print( ‘Item Removed:‘ , basket )

print( ‘Slice Removed:’ , basket )

Save then run this program – to see lists get manipulated

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.

Fixing lists

The values in a regular list can be changed as the program proceeds. Each element may be assigned a replacement value using the = assignment operator to specify the list name, element index number, and the replacement value. In programming terms the values stored in a regular list are “mutable” – they can be changed. Elements can also be dynamically added to a regular list, and dynamically removed from a regular list, as the program proceeds. This means that a regular list is ideal if your program will make changes to element values.

Where a list will only contain constant values, that will never change when the program runs, a fixed list can better be created. In programming terms, the values stored in a fixed list are “immutable” – they cannot be changed. Elements cannot be dynamically added to a fixed list, or dynamically removed from a fixed list, as the program proceeds. This means that a fixed list is ideal if your program will never make changes to element values.

Like index numbering, with lists the items in a tuple sequence are numbered from zero.

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

Regular list methods, such as sort() and reverse(), cannot be used on tuples but the built-in Python type() function can be used to reveal the data class type and the built-in len() function can be used to return the length of the tuple.

There must be the same number of variables as items to unpack a tuple.

Typically, a tuple is used to store values that are a collection of constant unchanging values such as day-of-the-week names, month-of-the-year names, or personal details of first name, last name, date-of-birth, address, phone number, etc.

tuple.py

Start a new program by initializing a tuple then display its class type

days = ( ‘Mon’ , ‘Tue’ , ‘Wed’ , ‘Thu’ , ‘Fri’ , ‘Sat’ , ‘Sun’ )

print( ‘days:’ , type( days ) )

Next, display the entire contents of the tuple, its length, and the value stored in its first element

print( ‘Days of the week:’ , days )

print( ‘No. of days in week:’ , len( days ) )

print( ‘Start day of week:’ , days[0] )

Now, initialize another tuple containing some personal details of a user

user = ( ‘John’ , ‘Doe’ , ‘Paris’ , ‘555-1234’ )

Then, display the user’s full name

print( ‘Name:’ , user[0] , user[1] )

Finally, display the user’s phone number

print( ‘Phone:’ , user[3] )

Save then run this program – to see the tuple values

A tuple may contain items that are not unique to its other elements.

Setting lists

The values in a regular list or a fixed list tuple can be repeated in its elements, 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 (braces) like this:

phonetic_set = { ‘Alpha’ , ‘Bravo’ , ‘Charlie’ }

A set may not contain items that are not unique to its other elements.

Unlike regular lists or tuples, individual elements in a set cannot be referenced using the set name followed by square brackets containing an index number. Instead, sets have powerful methods that can be dot-suffixed to the set name for manipulation and comparison of values:

 Set Method: Description: 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( i ) Removes item at position i from the set set1.intersection(set2) Returns items that appear in both sets set1.difference(set2) Returns items in set1 but not in set2

The built-in Python type() function can be used to reveal the data class type and the built-in len() function can be used to return the length of the set. Additionally, the Python built-in membership operator in can be used to find values in a set.

More set methods can be found in the Python documentation online at docs.python.org

Typically, a set is used to store unique values that are a collection of changeable values, which can easily be searched and compared using the powerful set methods. Although you cannot access set element values by index, a set can be converted to a regular list using the Python built-in list()function to allow element access.

set.py

Start a new program by initializing a set with unique name values then display its class type

party_goers = { ‘Andrew’ , ‘Barbara’ , ‘Carole’ , ‘David’ }

print( ‘party_goers:’ , type( party_goers ) )

Next, add statements to search the set elements for two specified values

print( ‘Did David go to the party?’ , ‘David’ in party_goers )

print( ‘Did Kelly go to the party?’ , ‘Kelly’ in party_goers )

Now, initialize another set with unique name values

students = { ‘Andrew’ , ‘Kelly’ , ‘Lynn’ , ‘David’ }

Then, create a further set containing only common values that appear in both previous sets

commons = party_goers.intersection( students )

Initialize a regular list of the common values – so the elements values can be individually accessed

party_students = list( commons )

Finally, display all common values and the value stored in the first regular list element

print( ‘Students at the party:’ , party_students )

print( ‘First student at the party:’ , party_students[0] )

Save then run this program – to see the set values

Notice that the list() function may not place element values in the same order as they appear in the set.

Naming elements

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 (braces) 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.

In other programming languages a list is often called an “array” and a dictionary is often called an “associative array”.

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.

Dictionaries are the final type of data container available in Python programming. In summary, the various types are:

Variable – stores a single value

List – stores multiple values in an ordered index array

Tuple – stores multiple fixed values in a sequence

Set – stores multiple unique values in an unordered collection

Dictionary – stores multiple unordered key:value pairs

Data is frequently associated as key:value pairs – for example, when you submit a web form a text value typed into an input field is typically associated with that text field’s name as its key.

dict.py

Start a new program by initializing a dictionary then display its data class type and its key:value contents

info = { ‘name’ : ‘Bob’ , ‘ref’ : ‘Python’ , ‘sys’ : ‘Win’ }

print( ‘info:’ , type( info ) )

print( ‘Dictionary:’ , info )

Next, display a single value referenced by its key

print( ‘\nReference:’ , info[ ‘ref’ ] )

Now, display all keys within the dictionary

print( ‘\nKeys:’ , info.keys() )

Delete one pair from the dictionary and add a replacement pair then display the new key:value contents

del info[ ‘name’ ]

info[ ‘user’ ] = ‘Tom’

print( ‘\nDictionary:’ , info )

Finally, search the dictionary for a specific key and display the result of the search

print( ‘\nIs There A name Key?:’ ,’name’ in info )

Save the file then run this program – to see the dictionary keys and values

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

Summary

•Multiple variables can be initialized in a single statement using a sequence of = assignments

•A Python list is an array variable that can store multiple items of data in sequentially numbered elements that start at zero

•Data stored in a list element can be referenced using the list name followed by an index number in [ ] square brackets

•A list element can have more than one index to represent multiple dimensions, such as X and Y coordinates

•List variables have a number of methods that can be dot-suffixed to the list name for manipulation

•The len() function returns the length of a specified list

•An individual list element can be deleted by specifying the list name and element index number to the Python del keyword

•A Python tuple is an immutable list whose values can be assigned to individual variables by “sequence unpacking”

•Data stored in a tuple element can be referenced using the tuple name followed by an index number in [ ] square brackets

•A Python set is an ordered collection of unique elements whose values can be compared and manipulated by its methods

•Data stored in a set cannot be referenced by its index number

•Set variables have methods that can be dot-suffixed to the list name for manipulation and comparison

•The Python built-in membership in operator can be used to seek a value within a set

•A set can be converted to a regular list using the list() function to allow reference of element data by index number

•A Python dictionary is a list of key:value pairs of data in which each key must be unique

•Data stored in a dictionary element can be referenced using the dictionary name followed by its key in [ ] square brackets

﻿