Python Programming/Lists
This lesson introduces Python lists.
Objectives and Skills
editObjectives and skills for this lesson include:[1]
- Data Structures
- List
Readings
editMultimedia
editExamples
editLists
editPython 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
editList 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
editLists 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
editLists 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
editList 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
editMulti 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
editLists 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
editThe 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
editThe 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
editTutorials
edit- Complete one or more of the following tutorials:
- LearnPython
- TutorialsPoint
- Codecademy
- Wikiversity
- Wikibooks
Practice
edit- 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.
- 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.
- 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.
- 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
editList Concepts
edit- 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- 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- 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-
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.
-
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.
-
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 '<>'.
-
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.
-
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.
-
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.
-
Python lists can be written as _____.Python lists can be written as a list of comma-separated values (items) between square brackets.
-
Lists might contain _____.Lists might contain items of different types, but usually the items all have the same type.
-
List items can be accessed by index using the syntax _____.List items can be accessed by index using the syntax list[index].
-
Lists support concatenation using the syntax _____.Lists support concatenation using the syntax list + list.
-
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.
-
List items are mutable, i.e. _____.List items are mutable, i.e. it is possible to change their content.
-
Multidimensional lists are _____.Multidimensional lists are lists within lists, accessed using the syntax list[index][index].
-
list.append(x) - _____.list.append(x) - Adds an item to the end of the list.
-
list.insert(i, x) - _____.list.insert(i, x) - Inserts an item at a given position.
-
list.remove(x) - _____.list.remove(x) - Removes the first item from the list whose value is x.
-
list.reverse() - _____.list.reverse() - Reverse the elements of the list in place.
-
list.sort() - _____.list.sort() - Sorts the items of the list in place.
-
list.clear() - _____.list.clear() - Removes all items from the list.
-
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.
-
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- Flashcards: Quizlet: Python Lists
- Flashcards: Quizlet: Python List Methods
- Flashcards: Quizlet: Python List Operations
- Quiz: Quizlet: Python Lists
- Quiz: Quizlet: Python List Methods
- Quiz: Quizlet: Python List Operations
See Also
editReferences
edit- ↑ Vskills: Certified Python Developer
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ PythonProgramming.net: Multi-dimensional lists
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Split
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: List (abstract data type)
- ↑ Wikipedia: Array
- ↑ Wikipedia: List (abstract data type)
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ Python.org: Lists
- ↑ PythonProgramming.net: Multi-dimensional lists
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Data Structures
- ↑ Python.org: Split
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ PythonLearn: Lists
- ↑ Wikipedia: Queue (abstract data type)
- ↑ PythonLearn: Lists
- ↑ Wikipedia: Queue (abstract data type)