Added code for lecture 2026-11-10
This commit is contained in:
parent
5b630435ae
commit
07b9e54bf0
52 changed files with 1248 additions and 1 deletions
56
lecture20261110/List-Intro_0001.py
Normal file
56
lecture20261110/List-Intro_0001.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
# List-Intro_0001.py
|
||||
#
|
||||
# A Python List is a type of variable which may contain
|
||||
# zero or more values (could be numbers, strings, etc.)
|
||||
# in an ordered manner. Each value can be accessed using
|
||||
# an index. Here are some examples of python list variables:
|
||||
#
|
||||
myList1 = [] # an empty list
|
||||
myList2 = [16, 8, 4, 2, 1] # a typical list
|
||||
myList3 = ["Boston", 23.5, "Pantera", "Los Lobos"]
|
||||
myList4 = [1, 10, 100, 1000, 10000, 100000, 1000000]
|
||||
myList5 = [5, 6, myList4, 8, 10]
|
||||
myList6 = ["item0", "item1", "item2", "item3", "item4"]
|
||||
|
||||
print(myList1, "\n", myList2, "\n", myList3, "\n", myList4, "\n", myList5, "\n", myList6)
|
||||
|
||||
# Finding the length of a list len(list variable name):
|
||||
print("Length of myList1 = ", len(myList1))
|
||||
print("Length of myList3 = ", len(myList3))
|
||||
print("Length of myList4 = ", len(myList4))
|
||||
print("Length of myList6 = ", len(myList6))
|
||||
|
||||
# List indices begin at 0 and end with len(list variable name) - 1
|
||||
print(myList4[0], "\n", myList4[3], "\n", myList6[4])
|
||||
|
||||
# Grabbing more than one list item is called slicing:
|
||||
print(myList2[0], "\n", myList4[2:5], "\n", myList4[3:])
|
||||
print(myList6[-3:])
|
||||
|
||||
print("Adding and removing list items ...")
|
||||
# How does one add or remove items from a list?
|
||||
# append() Adds an item to the end of the list:
|
||||
print(len(myList2), " : ", myList2)
|
||||
myList2.append(0)
|
||||
print(len(myList2), " : ", myList2)
|
||||
|
||||
# insert() Adds an item at a specific index
|
||||
print(len(myList3), " : ", myList3)
|
||||
myList3.insert(2, "Jeff Beck")
|
||||
print(len(myList3), " : ", myList3)
|
||||
|
||||
print("Other list operations include: extend(), remove(), pop(), & del()")
|
||||
|
||||
print("You can also sort lists")
|
||||
# You can also sort lists:
|
||||
print(myList2)
|
||||
myList2.sort()
|
||||
print(myList2)
|
||||
myList2.sort(reverse = True)
|
||||
print(myList2)
|
||||
|
||||
print("Indexing a list of lists ...")
|
||||
# You can have multi-dimensional lists (i.e. list of lists):
|
||||
print(myList5)
|
||||
print(myList5[2])
|
||||
print(myList5[2][5])
|
||||
Loading…
Add table
Add a link
Reference in a new issue