Back Python Chrestomathics Ahead |
Part 7 — Lists
Lest we go forward — Without knowing about lists — We would be wanting
Section 7.1 Basics
- A Python list is an ordered sequence of elements — there is a first element, second element, and so on. The word array is often used by programmers as a synonym for list.
- As with strings, the first element of a list has index 0, the second element has index 1, and so on. Therefore, the last element in a list with n elements has index n-1.
- You can create a new empty list by using empty brackets. The below statement makes
values
a list with no elements. The code snippets in this section are from program list_basics.py.
# create an empty list
values = []
- You can populate a new list by putting values within the brackets. The below snippet initializes
stuff
to be a three-element list andnumbers
to be a five-element list. Unlike some programming languages, Python does not require its list elements have the same type.
# create some non-empty lists
stuff = [ "abc", 1112, 2.71 ]
numbers = [ 14, 12, 27, 31, 24 ]
- The
len()
function works on lists. When used that way, it returns the number of elements in its list argument. The below snippet initializesnv
,ns
, andnv
respectively to 0, 3, and 5.
# determine lengths
nv = len( values )
ns = len( stuff )
nn = len( numbers )
print( "nv:", nv )
print( "ns:", ns )
print( "nn:", nn )
Its output confirms this intitialization.
nv: 0
ns: 3
nn: 5
- The brackets operator works on lists in the same way as it does on strings. If there is a single integer within the brackets, then the integer is used as an index to determine the list value of interest. Suppose variables
i
andj
are initialized to 1 and 2.
# set indices
i = 2
j = 4
Then the below code initializes
x
andy
to 27 and 24.
# access elements
x = numbers[ i ]
y = numbers[ j ]
print( "x:", x )
print( "y:", y )
The output confirms the initialization.
x: 27
y: 24
- Unlike strings, lists are mutable — the values of individual elements can change, and elements can be deleted, inserted, or appended. The below statement resets the third value in
numbers
from 27 to 25.
numbers[ 2 ] = 25
- If a colon (
:
) appears within the brackets, then a new list is created through slicing. The below statement setsitems
to be a copy of those elements ofnumbers
with indices 1 through 3; that is[12, 25, 31]
.
# slice
items = numbers[ 1 : 4 ]
- Built-in functions
max()
andmin()
can be used to determine the smallest and largest values in a list. The below code sets variablesa
andb
to 12 and 31.
# get min and max
a = min( numbers )
b = max( numbers )
print( "a:", a )
print( "b:", b )
The snippet shows these values in its output.
a: 12
b: 31
Naming gotchas
|
- Lists can be displayed using function
print()
. The below code segment prints the example lists.
print( "values:", values )
print( "stuff:", stuff )
print( "numbers:", numbers )
print( "items:", items )
- The code segment outputs
values: []
stuff: ['abc', 1112, 2.71]
numbers: [14, 12, 25, 31, 24]
items: [12, 25, 31]
Section 7.2 — List methods for adding and counting elements
- Lists have many method functions to inspect and manipulate the list. The code demonstrations in this section are from program list_add_count.py. The program begins with a request for text from the user. The reply is split into a list of words and printed.
# get example text
reply = input( "Enter text: " )
words = reply.split()
print( "words:", words )
- Suppose the user responds as below.
Enter words: better today means better tomorrow
- Then
words
will be below the list.
words: ['better', 'today', 'means', 'better', 'tomorrow']
- To append a value to the end of a list, use list method function
append()
. The next statement updateswords
to have a sixth element equal to"okay"
.
# append a word
words.append( "okay" )
- The list
words
is now
words: ['better', 'today', 'means', 'better', 'tomorrow', 'okay']
- There is list method function
insert()
to place a new element at an indicated index. The function takes two arguments, the index and element value of interest.
# insert a word
words.insert( 3, "a" )
- The list
words
is now
words: ['better', 'today', 'means', 'a', 'better', 'tomorrow', 'okay']
- There is also a list method function
count()
that takes a single argument. The list returns the number of elements equal to the argument.
# search words
n1 = words.count( "better" )
n2 = words.count( "e" )
- The values of
n1
andn2
are respectively 2 and 0.
n1: 2
n2: 0
Counting gotcha
|
Section 7.3 — List methods for deleting elements
- Lists have two methods for removing elements —
pop()
andremove()
. The code demonstrations in this section are from program list_delete_methods.py. The program begins with some request for input from the user.
# get example text
reply = input( "Enter text: " )
words = reply.split()
reply = input( "Enter index: " )
i = int( reply )
w = input( "Enter word: " )
- The inputs are used to get a lists of words
w
, an indexi
, and a word of interestw
.
- Suppose the user responds as below.
Enter text: abc acb bac bca cab cba
Enter index: 4
Enter word: bac
- Then the values of
words
,i
, and aw
are
words: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
i: 0
w: bac
- List method
pop()
has an optional index parameter. If an index is supplied, then the element at that index is deleted from the list. If no index is supplied, then the last element in the list is deleted. Either way, the method returns the value of the deleted element.
- The below code segment shows both ways to use method
pop()
.
# pop some elements
popped1 = words.pop( i )
popped2 = words.pop( )
- As variable
i
has value 0, the program run removes the first and last elements fronwords
and initializes variablespopped1
andpopped2
to those former list values.
popped1: abc
popped2: cba
words after removing popped1 and popped2: ['acb', 'bac', 'bca', 'cab']
- List method
remove()
expects as its argument one of the values from its list. If such a value is given, the first occurence of the value is deleted from the list.
# remove element with value w
words.remove( w )
- After the above statement executes
words
now equals
words after removing w: ['acb', 'bca', 'cab']
Removing gotchas
|
- If it becomes necessary to remove all elements from a list, then use method
clear()
as shown below.
# clear out all the elements
words.clear()
- After the statement runs
words
has no elements.
words after clearing: []
Section 7.4 What’s next
- We next turn our attention to statements that support repeated execution of their actions
Back Python Chrestomathics Ahead |