☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents
Subscribe Contact


Contents

Overview

So far, we have used variables to store various data types. We have learned that Python is dynamically typed and that a variable can hold one value at a time. We also learned that a variable is a label for a memory location in the computer where the value assigned to that variable is stored. Next, we will take the concept of a variable and expand on it so that we can use a single variable to refer to multiple data values at once. We do this through the use of data structures. The first data structure we will explore in Python is a list.

Concept: List
Full Concepts List: Alphabetical  or By Chapter 

In Python, a list is a versatile, mutable (changeable) data structure that allows you to store a collection of items. Lists are ordered, meaning that the items in the list appear in a specific sequence, and this order is maintained throughout the life of the list. One of the key characteristics of a list is its mutability: you can modify its content by adding, removing, or changing items. Lists are created by placing items (elements), which can be of any data type, inside square brackets [], separated by commas. For example, my_list = [1, 2, 'apple', 'banana'] contains two integers and two strings. Python lists are also dynamic; they can grow or shrink as needed. They support a range of operations like slicing (to extract parts of the list), iterating (looping through each item in the list), and nested lists (lists within lists). Lists are one of Python's most commonly used data structures due to their flexibility and ease of use, making them suitable for a wide range of applications, from simple data storage to complex data manipulations.

The List Data Structure

Lists are one of the most commonly used data structures in Python. They allow us to store multiple data elements together using one variable name. Here are the key attributes of the list data structure:


List Attribute Description
Heterogeneous Lists are heterogeneous, that is; they can store different values of different data types at the same time.
Ordered The items in a list are in a set order and remain that way unless we use a List Method  to alter that order.
Mutable The items in a list are mutable (changeable), that is, they can be changed, added, and removed after they have been added to the list.
Allows Duplicates Since lists are indexed, which provides a unique identifier for any given item in the list, list item values can be duplicates of each other.
Indexed Lists are indexed from [0] to [length - 1], so the first item in the list is list_var[0], the second is list_var[1], etc.
Are Objects Lists are objects in Python, so they have methods  and can be managed like any other object in the language.
Have Methods Because lists are objects, they have methods. You can find a complete list of list methods here .
Can Be Nested Lists can contain lists, that is, any list element can be a list.


Lists & Memory (RAM)

To review, a variable is a label for a storage location in memory where the value we have assigned to that variable resides. We have seen the diagram in Figure 1 before. It depicts a variable called age, which is assigned the value of 25. The label age points to a location in memory where 25 is stored.



Figure 1: Variables and memory

Lists & Memory: When we want to create a list in Python, we start by creating a variable and using the assignment operator (=) to initialize our list with values. In Figure 2, we see that we're a variable my_list. We defined a list on the right side of the assignment operator, which in this example contains three values (strings): apple, orange, and pear. The list variable points to a memory address, which is the address of a block memory. Inside that block of memory, our list values are stored. We only need to use the variable and indexes (in this example, [0], [1], and [2]) to access any item in the list.



Figure 2: Lists and memory

Creating Lists

Creating a list is similar to creating a variable and assigning a value to it; however, instead of one value, a list variable can be assigned a set of values. That set of values is enclosed inside square brackets [ ] on the right side of the assignment operator (=). Here is the general form of creating a list:

list_variable = [iterable(s)]

Here are several code examples:

# Empty list
my_list = []

# List of integers
int_list = [2, 4, 6, 8]

# List of strings
dow_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

# Heterogeneous list
employee = [12345678, "Bob", "Smith", "Marketing", 25, 23.50, True]

# Nested (Multi-Dimensional) List (list of lists)
nested_list = [["Apple", "Cherry", "Pear"], 99, [True, False, True], 44.599]

Code Details:

List Indexing

The items stored in lists are accessible through list indexes, similar to the indexing we learned earlier with strings. Each item in a list has an index value denoted as an integer inside of square brackets [ ]. Like strings, indexing of lists starts at zero [0] and counts by 1 up to the end of the list [list_length - 1]. We can also access indexes using negative numbers, beginning from the end of the list and counting backward toward the beginning of the list.

Figure 3 depicts the five lists created in the code above:



Figure 3: List indexing

Accessing List Items

Let's expand on the code above for creating the lists to demonstrate how to access items in those lists:

# Empty list
my_list = []
print(my_list)
print()

# List of integers
int_list = [2, 4, 6, 8]
print(int_list)
print(int_list[3])
print(int_list[0:2])
print()

# List of strings
dow_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
print(dow_list)
print(dow_list[-2])
print(dow_list[3:5])
print()

# Heterogeneous list
employee = [12345678, "Bob", "Smith", "Marketing", 25, 23.50, True]
print(employee)
hourly_rate = employee[5]
print(hourly_rate)
print()

# Nested (Multi-Dimensional) List (list of lists)
nested_list = [["Apple", "Cherry", "Pear"], 99, [True, False, True], 44.599]
print(nested_list)
print(nested_list[0])
print(nested_list[0][1])
print(nested_list[1])
print(nested_list[2][1])

Output:

[]

[2, 4, 6, 8]
8
[2, 4]

['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Thursday
['Thursday', 'Friday']

[12345678, 'Bob', 'Smith', 'Marketing', 25, 23.5, True]
23.5

[['Apple', 'Cherry', 'Pear'], 99, [True, False, True], 44.599]
['Apple', 'Cherry', 'Pear']
Cherry
99
False

Code & Output Details:

Updating (Changing) Lists

Once we have created a list, we can update (change) the values of list items. Remember that we can make those changes because lists are mutable (changeable). To change the value of any existing item(s) in a list we use the list name and the index(es) of the items we want to change, the assignment operator (=), and then the new value(s). Notice the plurals in that sentence, we can update one item in a list or multiple items in a list using indexes and slices.

Examples:

num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(num_list)
num_list[9] = 10
print(num_list)
num_list[4:6] = [99, 98, 97]
print(num_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 99, 98, 97, 7, 8, 9, 10]

Code & Output Details:

Adding List Items

We can also add new items to a list, which changes its size, and again is possible because lists are mutable (changeable). There are several approaches to adding items to a list: the List Methods  append(), extend(), and insert() and also using concatenation.

Examples:

num_list = [1, 2, 3, 4, 5]
print(num_list)
# Add 2 items using append() list method twice
num_list.append(111)
num_list.append(222)
print(num_list)
# Add several items at once using extend() method
num_list.extend([333, 444, 555])
print(num_list)
# Insert items using the insert() list menthod
num_list.insert(0, 666)
print(num_list)
num_list.insert(7, 777)
print(num_list)
# Use concatenation to add items to the list
num_list = num_list + [1000, 1001]
print(num_list)

Output:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 111, 222]
[1, 2, 3, 4, 5, 111, 222, 333, 444, 555]
[666, 1, 2, 3, 4, 5, 111, 222, 333, 444, 555]
[666, 1, 2, 3, 4, 5, 111, 777, 222, 333, 444, 555]
[666, 1, 2, 3, 4, 5, 111, 777, 222, 333, 444, 555, 1000, 1001]

Code & Output Details:

Removing (Deleting) List Items

We can remove items from a list, which changes its size, and again is possible because lists are mutable (changeable). There are several approaches to removing items from a list: the list methods  remove(), pop(), and clear() and also using del Python command (keyword).

Example 1:

str_list = ["AA", "BB", "CC", "DD", "EE", "FF"]
print(str_list)
# Delete one item from list using del
del str_list[2]
print(str_list)
# Delete two items from the list using del & slicing
del str_list[3:5]
print(str_list)
# Delete the entire list using del, which also removes
# the variable from memory so the list is no longer
# accessible in the program.
del str_list
print(str_list)

Output 1:

['AA', 'BB', 'CC', 'DD', 'EE', 'FF']
['AA', 'BB', 'DD', 'EE', 'FF']
['AA', 'BB', 'DD']
Traceback (most recent call last):
File "C:\Users\john\PycharmProjects\DemoProject\Demo.py", line 16, in 
print(str_list)
NameError: name 'str_list' is not defined

Example 1 Code & Output Details:

Example 2:

str_list = ["AA", "BB", "CC", "DD", "EE", "FF"]
print(str_list)
# Use remove() list method  to remove the first
# instance of the value specified, in this case,
# the first instance of "BB" is removed
str_list.remove("BB")
print(str_list)
# Use pop() to pop the value at index 3, which
# removes it from the list and also returns
# the value stored at that index
val = str_list.pop(3)
print(str_list)
print(val)
# Use pop() with no specified value, which
# removes the last item in the list and also
# returns the value stored there
val = str_list.pop()
print(str_list)
print(val)
# Use the clear() list method  to empty the
# list. The list variable remains in memory
# so we can continue to use it.
str_list.clear()
print(str_list)

Output 1:

['AA', 'BB', 'CC', 'DD', 'EE', 'FF']
['AA', 'CC', 'DD', 'EE', 'FF']
['AA', 'CC', 'DD', 'FF']
EE
['AA', 'CC', 'DD']
FF
[]

Example 2 Code & Output Details:

Additional List Methods 

We've seen several list methods  so far in the examples above. There are other list methods  available as well. Here are some examples of other list methods  and their uses:

Examples:

int_list1 = [1, 2, 3, 4, 5]
int_list2 = [1, 2, 5, 4, 5]
# Copy a list
print(int_list1)
new_int_list = int_list1.copy()
print(int_list1)
print(new_int_list)
print()
# Count how many times a specified
# value appears in a list
print(int_list2.count(5))
# Reverse the items in a list
print(int_list1)
int_list1.reverse()
print(int_list1)
print()
# Sort a list
print(int_list2)
int_list2.sort()
print(int_list2)

Output:

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

2

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

[1, 2, 5, 4, 5]
[1, 2, 4, 5, 5]

Code & Output Details:

Built-In Python Functions & Operators with Lists

In addition to list methods , we can also use many Built-In Functions  and Operators  with lists as well. We saw one of the functions already above, del, which we used to delete a list. Here are some examples of other built-in functions and operators used with lists, including len(), max(), min(), in, =, ==, and +.

Examples:

# Built-In Functions
int_list1 = [1, 2, 3, 4, 5]
# Determine the length of a list
print(len(int_list1))
# Determine the max value in a list
print(max(int_list1))
# Determine the minimum value in a list
print(min(int_list1))
# Determine if a specified value is in a list
print(2 in int_list1)
print(99 in int_list1)

# Operators
# Determine if two lists are the same
# using the equality operator
int_list2 = [1, 2, 3, 5, 4]
print(int_list1 == int_list2)
int_list1.sort()
int_list2.sort()
print(int_list1 == int_list2)
# Combine two lists together Using
# the + (addition/concatenation)
# Operator
print(int_list1 + int_list2)

Output:

5
5
1
True
False
False
True
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Code & Output Details:

Practice Problems

Problem 1

Write a Python program that creates a list containing 10 integers. Then, using individual print statements, print the first element, the third element, and the tenth element.


Problem 2

Write a Python program that creates a list containing the following words as individual list elements.

field
the
across
horse
dog
cow
walked
pasture
flew
over
to
a
bird
barn
ran
house

Then, use a single print statement to print a sentence of at least four words from the list. The first word of your output sentence should be appropriately capitalized, so use the appropriate string method to do so. Also, use the appropriate print function argument to add a period at the end of your output sentence. You can reuse any of the words as necessary. No hardcoding!


Problem 3

Write a Python program that does the following:

  1. Create a list containing five integers.
  2. Print the list.
  3. Print the length of the list.
  4. Print the minimum value in the list.
  5. Print the maximum value in the list.
  6. Reverse the list.
  7. Print the reversed list.
  8. Add five more values to the list.
  9. Print the list.
  10. Print the length of the list.
  11. Print the minimum value in the list.
  12. Print the maximum value in the list.
  13. Sort the list.
  14. Print the list.
  15. Delete the fourth item in the list.
  16. Print the list.
  17. Delete the seventh items in the list.
  18. Print the list.

Problem 4

Write a Python program that creates a heterogeneous list containing the following data elements for an employee: First Name (string), Last Name (string), Address (string), City (string), State (string), Zip Code (string), Phone Number (string), Email Address (string), Age (int), Hourly Wage (float), and a boolean indicator of whether the employee receives bonuses. You can use any data values you wish for the list elements. Then, write a single print statement that prints the list item in the format shown in the example shown below.

Bob Smith
1234 Someplace Street
Some City, UT 84999
(801)999-4444
bob@abc.com
Age: 40
Wage: 25.99/hourly
Bonuses: False


-->

 


«  Previous : Data Structures : Concepts
Next : Data Structures : Dictionaries  »



© 2023 John Gordon
Cascade Street Publishing, LLC