Python Programming/Lists

From Wikiversity
Jump to navigation Jump to search

This lesson introduces Python lists.

Objectives and Skills[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Data Structures
    • List

Readings[edit | edit source]

  1. Wikipedia: List (computer science)
  2. Python for Everyone: Lists

Multimedia[edit | edit source]

  1. YouTube: Python for Informatics - Chapter 8 - Lists
  2. YouTube: Python Lists
  3. YouTube: Immutable vs Mutable Objects in Python

Examples[edit | edit source]

Lists[edit | edit source]

Python supports a number of compound data types used to group other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.[2]

list = [1, 2, 3]

for item in list:
    print(item)

Output:

1
2
3

Index[edit | edit source]

List items can be accessed by index.[3]

list = [1, 2, 3]

for i in range(len(list)):
    print("list[%d]: %d" % (i, list[i]))

Output:

list[0]: 1
list[1]: 2
list[2]: 3

Concatenation[edit | edit source]

Lists support concatenation.[4]

list = [1, 2, 3]

list += [4, 5]
for i in range(len(list)):
    print("list[%d]: %d" % (i, list[i]))

Output:

list[0]: 1
list[1]: 2
list[2]: 3
list[3]: 4
list[4]: 5

Slicing[edit | edit source]

Lists may be sliced.[5]

list = [1, 2, 3, 4, 5]

list = list[0:2] + list[3:]
for i in range(len(list)):
    print("list[%d]: %d" % (i, list[i]))

Output:

list[0]: 1
list[1]: 2
list[2]: 4
list[3]: 5

Mutable[edit | edit source]

List items are mutable, i.e. it is possible to change their content.[6]

list = [1, 2, 3]

for i in range(len(list)):
    list[i] = -list[i]
    print("list[%d]: %d" % (i, list[i]))

Output:

list[0]: -1
list[1]: -2
list[2]: -3

Multidimensional[edit | edit source]

Multi dimensional lists are lists within lists.[7]

table = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in range(len(table)):
    for column in range(len(table[row])):
        print(table[row][column], end = '\t')
    print()

Output:

1       2       3
4       5       6
7       8       9

Methods[edit | edit source]

Lists support a variety of methods, including:[8]

  • list.append(x) - Adds an item to the end of the list.
  • list.insert(i, x) - Inserts an item at a given position.
  • list.remove(x) - Removes the first item from the list whose value is x
  • list.reverse() - Reverse the elements of the list in place.
  • list.sort() - Sorts the items of the list in place.
  • list.clear() - Removes all items from the list.
list = []

print("List:", list)

list.append(1)
list.append(2)
print("After append:", list)

list.insert(2, 3)
list.insert(0, 4)
print("After insert:", list)

list.remove(4)
print("After remove:", list)

list.reverse()
print("After reverse:", list)

list.sort()
print("After sort:", list)

list.clear()
print("After clear:", list)

Output:

List: []
After append: [1, 2]
After insert: [4, 1, 2, 3]
After remove: [1, 2, 3]
After reverse: [3, 2, 1]
After sort: [1, 2, 3]
After clear: []

Stacks and Queues[edit | edit source]

The list.pop([i]) method removes the item at the given position in the list, and returns it. If no index is specified, pop() removes and returns the last item in the list.[9] This allows for simple stack (last-in, first-out) and queue (first-in, first-out) processing.

print("Stack: Last in, first out")
list = []
list.append(1)
list.append(2)
list.append(3)
while len(list) > 0:
    print(list.pop())

print("\nQueue: First in, first out")
list = []
list.append(1)
list.append(2)
list.append(3)
while len(list) > 0:
    print(list.pop(0))

Output:

Stack: Last in, first out
3
2
1

Queue: First in, first out
1
2
3

Split[edit | edit source]

The string split(<separator>) method returns a list of the words in the string, using separator as the delimiter string. If separator is not specified, runs of consecutive whitespace are regarded as a single separator.[10]

string = "This is a test"
list = string.split()
print(list)

string = "So-is-this"
list = string.split("-")
print(list)

Output:

['This', 'is', 'a', 'test']
['So', 'is', 'this']

Activities[edit | edit source]

Tutorials[edit | edit source]

  1. Complete one or more of the following tutorials:

Practice[edit | edit source]

  1. Create a Python program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a list. Finally, display the list of entered scores sorted in descending order and then calculate and display the high, low, and average for the entered scores. Include try and except to handle input errors.
  2. Create a Python program that asks the user to enter a line of comma-separated grade scores. Use the string split() method to parse the line and display the list of entered scores sorted in descending order and then calculate and display the high, low, and average for the entered scores. Include try and except to handle input errors.
  3. Create a Python program that asks the user to enter a line of text. Use the string split() method to parse the line and then display the list of words in alphabetical order with any duplicate words removed from the list.
  4. Create a Python program that asks the user for a line of text that contains HTML tags, such as:
        <p><strong>This is a bold paragraph.</strong></p>
    Use string methods to search for and remove all HTML tags from the text, saving each removed tag in a list. Print the untagged text and then display the list of removed tags sorted in alphabetical order with duplicate tags removed. Include error handling in case an HTML tag isn't entered correctly (an unmatched < or >). Use a user-defined function for the actual string processing, separate from input and output.

Lesson Summary[edit | edit source]

List Concepts[edit | edit source]

  • A list or sequence is a data type that represents an ordered sequence of values, where the same value may occur more than once.[11]
  • Lists are a basic example of containers, as they contain other values. If the same value occurs multiple times, each occurrence is considered a distinct item.[12]
  • A list can often be constructed by writing the items in sequence, separated by commas, semicolons, or spaces, within a pair of delimiters such as parentheses '()', brackets '[]', braces '{}', or angle brackets '<>'. [13]
  • Some languages may allow list types to be indexed or sliced like array types, in which case the data type is more accurately described as an array.[14]
  • An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.[15]
  • Lists can be used to store a list of elements. However, unlike in traditional arrays, lists can expand and shrink, and are stored dynamically in memory.[16]

Python Lists[edit | edit source]

  • Python lists can be written as a list of comma-separated values (items) between square brackets.[17]
  • Lists might contain items of different types, but usually the items all have the same type.[18]
  • List items can be accessed by index using the syntax list[index].[19]
  • Lists support concatenation using the syntax list + list.[20]
  • Lists may be sliced using the syntax list[start:end]. The slice will include the starting index value up to but not including the ending index value.[21]
  • List items are mutable, i.e. it is possible to change their content.[22]
  • Multidimensional lists are lists within lists, accessed using the syntax list[index][index].[23]
  • list.append(x) - adds an item to the end of the list.[24]
  • list.insert(i, x) - Inserts an item at a given position.[25]
  • list.remove(x) - Removes the first item from the list whose value is x.[26]
  • list.reverse() - Reverse the elements of the list in place.[27]
  • list.sort() - Sorts the items of the list in place.[28]
  • list.clear() - Removes all items from the list.[29]
  • list.pop([i]) removes the item at the given position in the list, and returns it. If no index is specified, pop() removes and returns the last item in the list.[30]
  • string.split(<separator>) returns a list of the words in the string, using separator as the delimiter string. If separator is not specified, runs of consecutive whitespace are regarded as a single separator.[31]

Key Terms[edit | edit source]

aliasing
A circumstance where two or more variables refer to the same object.[32]
delimiter
A character or string used to indicate where a string should be split.[33]
element
One of the values in a list (or other sequence); also called items.[34]
equivalent
Having the same value.[35]
index
An integer value that indicates an element in a list.[36]
identical
Being the same object (which implies equivalence).[37]
list
A sequence of values.[38]
list traversal
The sequential accessing of each element in a list.[39]
nested list
A list that is an element of another list.[40]
object
Something a variable can refer to. An object has a type and a value.[41]
queue
A data structure in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the end of the collection and removal of entities from the start of the collection (first-in, first-out).[42]
reference
The association between a variable and its value.[43]
stack
A data structure in which the entities in the collection are kept in order and the principal (or only) operations on the collection are push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed (last-in, first-out).[44]

Review Questions[edit | edit source]

Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. A list or sequence is _____.
    A list or sequence is a data type that represents an ordered sequence of values, where the same value may occur more than once.
  2. Lists are a basic example of _____. If the same value occurs multiple times, _____.
    Lists are a basic example of containers, as they contain other values. If the same value occurs multiple times, each occurrence is considered a distinct item.
  3. A list can often be constructed by _____. 
    A list can often be constructed by writing the items in sequence, separated by commas, semicolons, or spaces, within a pair of delimiters such as parentheses '()', brackets '[]', braces '{}', or angle brackets '<>'. 
  4. Some languages may allow list types to be _____ like array types, in which case the data type is more accurately described as an array.
    Some languages may allow list types to be indexed or sliced like array types, in which case the data type is more accurately described as an array.
  5. An array is _____.
    An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.
  6. Lists can be used to store a list of elements. However, unlike in traditional arrays, lists can _____, and are stored _____.
    Lists can be used to store a list of elements. However, unlike in traditional arrays, lists can expand and shrink, and are stored dynamically in memory.
  7. Python lists can be written as _____.
    Python lists can be written as a list of comma-separated values (items) between square brackets.
  8. Lists might contain _____.
    Lists might contain items of different types, but usually the items all have the same type.
  9. List items can be accessed by index using the syntax _____.
    List items can be accessed by index using the syntax list[index].
  10. Lists support concatenation using the syntax _____.
    Lists support concatenation using the syntax list + list.
  11. Lists may be sliced using the syntax _____.
    Lists may be sliced using the syntax list[start:end]. The slice will include the starting index value up to but not including the ending index value.
  12. List items are mutable, i.e. _____.
    List items are mutable, i.e. it is possible to change their content.
  13. Multidimensional lists are _____.
    Multidimensional lists are lists within lists, accessed using the syntax list[index][index].
  14. list.append(x) - _____.
    list.append(x) - Adds an item to the end of the list.
  15. list.insert(i, x) - _____.
    list.insert(i, x) - Inserts an item at a given position.
  16. list.remove(x) - _____.
    list.remove(x) - Removes the first item from the list whose value is x.
  17. list.reverse() - _____.
    list.reverse() - Reverse the elements of the list in place.
  18. list.sort() - _____.
    list.sort() - Sorts the items of the list in place.
  19. list.clear() - _____.
    list.clear() - Removes all items from the list.
  20. list.pop() - _____.
    list.pop() - Removes the item at the given position in the list, and returns it. If no index is specified, pop() removes and returns the last item in the list.
  21. string.split() - _____.
    string.split() - Returns a list of the words in the string, using separator as the delimiter string. If separator is not specified, runs of consecutive whitespace are regarded as a single separator.

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]