Lecture-22 Lists 24-25
COMP101 Introduction to Programming 2024-25: Lecture-22 Data Collections - Lists
Page 1: Overview
Introduction to data collections in programming.
Page 2: Data Assignments
Typically, one variable holds one data item:
Example:
name = 'stephen'
Can assign several related data items to one variable:
Example:
siblings = ['stephen', 'leszek', 'penny', 'victor', 'jenny']Relationship: siblings or students in a module.
Page 3: Types of Data Collections
Four main data types for storing multiple values:
List
Tuple
Set
Dictionary
Often called 'one-dimensional arrays' (1-D arrays).
They are data types similar to int, float, etc., used to store multiple related data items using a single variable name.
Page 4: Lists
Example:
siblingList = ['stephen', 'leszek', 'penny', 'victor', 'jenny']Characteristics:
Uses brackets
[ ].Ordered (indexed starting at 0).
Mutable (can change elements).
Duplicates allowed.
Mixed data types permitted.
Suitable for frequent additions, amendments, or deletions, but slower access for iteration.
Page 5: Tuples
Example:
siblingTuple = ('stephen', 'leszek', 'penny', 'victor', 'jenny')Characteristics:
Uses parentheses
( ).Ordered (indexed starting at 0).
Immutable (cannot change elements).
Duplicates allowed.
Mixed data types permitted.
Best for fixed sets of data, faster processing compared to lists for large datasets.
Page 6: Sets
Example:
siblingSet = {'stephen', 'leszek', 'penny', 'victor', 'jenny'}Characteristics:
Uses curly braces
{ }.Unordered (no indexing).
Immutable elements.
No duplicates allowed.
Mixed data types permitted.
Efficient for checking membership of items.
Page 7: Dictionaries
Example:
siblingDict = {'stephen': 'male', 'leszek': 'male', 'penny': 'female', 'victor': 'male', 'jenny': 'female'}Characteristics:
From Python v3.7 and above.
Called an 'associative array' (key: value pairs).
Ordered (has an index).
Mutable with no duplicates.
Fast processing for large volumes of data.
Data retrieval via its key.
Page 8: List Indexing and Access
Each list element has an index, starting at
[0]:Example:
siblingList = ['stephen', 'leszek', 'penny', 'victor', 'jenny']Accessing:
print(siblingList[2])givespenny.Individual characters can't be accessed; only entire elements.
Page 9: Modifying Lists
Example: Changing an element in a list:
To change
pennytobenny:siblingList[2] = 'benny'Result:
siblingListbecomes['stephen', 'leszek', 'benny', 'victor', 'jenny'].
Page 10: List to String Conversion
Use
' '.join(list)to convert list to a string:E.g.,
siblingString = ' '.join(siblingList), results instephen leszek benny victor jenny.Method separates each element by a space (or specified separator).
Page 11: String Representation
Example of converting list to string:
siblingString = ', '.join(siblingList)Converts to
stephen, leszek, benny, victor, jenny, indexes assigned to each character from 0 to 32.
Page 12: String to List Conversion - .split()
To convert string back to a list use
.split(separator):Example:
var = string_name.split(' ')retrieves access to change individual elements.
Page 13: Further String Splitting Example
Example:
siblingString = ' '.join(siblingList) splitList = siblingString.split()Converts back to the original list with indexes.
Page 14: List Slicing and Output
Example of slicing a list:
print(siblingList[1:3]) # Output: ['leszek', 'benny']The last index is excluded in slice notation.
Page 15: Extended Slicing Example
Accessing slices:
print(siblingList[:3]) # Output: ['stephen', 'leszek', 'benny'] print(siblingList[3:]) # Output: ['victor', 'jenny']
Page 16: Slicing with Stride
Using stride in slicing:
print(siblingList[::2]) # Output: ['stephen', 'benny', 'jenny']
Page 17: Extending Lists
Example of short names for each sibling:
steforstephen,lesforleszek, etc.
Page 18: Creating a New List with Short Names
Steps to create a list of short names:
Create a new list.
For each name, slice the first 3 characters.
Append to the new list.
Page 19: Looping through List to Slice Names
Example:
familiarList = [] for i in siblingList: familiarList.append(i[:3]) print(familiarList) # Output: ['ste', 'les', 'ben', 'vic', 'jen']
Page 20: Concatenating Two Lists
Create a third list to combine full names and short names:
siblingFamiliar = [] for i in range(len(siblingList)): siblingName = siblingList[i] + ' ' + familiarList[i] siblingFamiliar.append(siblingName) print(siblingFamiliar) # Output: ['stephen ste', 'leszek les', ...]
Page 21: Concatenation Explained
The concatenation combines full names with their short forms:
Using a
+operator allows for combined elements.
Page 22: Basic List Concatenation
Example of concatenating different lists:
listNum = [1, 2, 3] listStr = ['a', 'b', 'c'] combined = listNum + listStr print(combined) # Output: [1, 2, 3, 'a', 'b', 'c']
Page 23: Creating and Populating Lists
Example of creating and populating an empty list:
spectrumList = ['red', 'orange', 'green', 'blue']Items can be any type and mixed types are allowed.
Page 24: List Output
Output full list and one item:
print(spectrumList) # Output: ['red', 'orange', 'green', 'blue'] print(spectrumList[2]) # Output: green
Page 25: Slicing for Output
Example of slicing for several items:
print(spectrumList[1:3]) # Output: ['orange', 'green']
Page 26: Adding Items by Index
Adding items at specific indices:
spectrumList[2:2] = ['yellow'] print(spectrumList) # Output: ['red', 'orange', 'yellow', 'green', 'blue']
Page 27: Inserting Items
Example of inserting an item anywhere in a list:
spectrumList.insert(0, 'colours') print(spectrumList) # Output includes 'colours' at start.
Page 28: Appending Items
Using
.append()to add to the end of the list:spectrumList.append('indigo') print(spectrumList) # Output with 'indigo' last.
Page 29: Deleting Items by Index
Using
delto delete items:del spectrumList[1] # Removes 'orange'
Page 30: Removing by Value
Example of using
.remove():spectrumList.remove('blue') print(spectrumList) # Removes the first 'blue' occurrence.
Page 31: List Functions
Count items with
len():print(len(spectrumList)) # Output the length of spectrum list.Sum numeric items using
sum():numList = [1, 2, 3] print(sum(numList)) # Output the total sum.
Page 32: Lists Summary
Example of user-defined lists:
num_list = [1, 2, 3, 4] animal_list = ['cat', 'dog', 'cow', 'big bird']Lists are ordered and indexed.
Page 33: Accessing List Items
Reference to an item is via its index:
List indexing behavior explained:
First index is always
[0].Example shown for
animalListaccess.