CSEN102 Introduction to Computer Science: Lecture 6: More Lists in Python

This lecture for CSEN102: Introduction to Computer Science, given by Milad Ghantous, PhD, is a continuation of the topic of lists, with a specific focus on their implementation and usage in Python.


6.1 Review of Lists

As discussed in previous lectures, a list (or array in some languages) is a data structure used to store a collection of items. In Python, lists are versatile and can hold items of different data types, making them powerful for various programming tasks.


6.2 Creating Lists in Python

Lists in Python are created by placing all the items (elements) inside square brackets `[]`, separated by commas.

Empty List:

my_list = []

List with Integers:

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

List with Mixed Data Types:

Python lists can contain elements of different data types within the same list.

mixed_list = [1, "hello", 3.14, True]

Nested Lists:

A list can also contain other lists as elements, creating nested structures (like a 2D array).

nested_list = [1, 2, [3, 4]]

6.3 Accessing Elements in Python Lists

Elements in a Python list are accessed using indexing. Positive indices start from 0 for the first element, and negative indices can be used to access elements from the end of the list (-1 for the last element).

Positive Indexing:

my_list = ['p', 'y', 't', 'h', 'o', 'n']
print(my_list[0]) # Output: p
print(my_list[2]) # Output: t

Negative Indexing:

my_list = ['p', 'y', 't', 'h', 'o', 'n']
print(my_list[-1]) # Output: n
print(my_list[-3]) # Output: h

Slicing Lists:

You can access a range of elements in a list using the slicing operator `[:]`.

my_list = ['p', 'y', 't', 'h', 'o', 'n']
print(my_list[1:4]) # Output: ['y', 't', 'h']
print(my_list[:3])  # Output: ['p', 'y', 't']
print(my_list[3:])  # Output: ['h', 'o', 'n']

6.4 Modifying Lists

Since Python lists are mutable, you can change their elements, add new ones, or remove existing ones.

Changing Elements:

my_list = [1, 2, 3]
my_list[0] = 5
print(my_list) # Output: [5, 2, 3]

Adding Elements:

Removing Elements:


6.5 List Methods (Common Built-in Functions)

Python lists have several built-in methods for common operations.