Thursday, June 30, 2022

Python - Lists

thislist = ["apple", "banana", "cherry"]

# Displays all the items in the list
print(thislist)

# Displays only index item 0 of the list (apple)
print(thislist[0])

# How many items in the list?
# 3
print(len(thislist))

list1 = ["abc", 34, True, "Pecan"]
print(list1)

# class 'list'
print (type(thislist))

# Negative indexing
# cherry
print(thislist[-1])

#            0       1        2          3     4       5       6
bigList = ["Adam", "Bob", "Charlie", "David", "Ed", "Frank", "Greg" ]
# Charlie, David, Ed
# So confusing.  Stops before the upper end
# W3schools says: "Start at index 2 (included) and end at index 5 (not included)
print(bigList[2:5])

# Ends at index 3 (not included)
# Adam Bob Charlie
print(bigList[:3])

# Starts at index 3 and goes to the end
# David Ed Frank Greg
print(bigList[3:])

# Starts with Ed, three from the end
# Ends with the last one, but does not include the last one
# So winds up being:
#    Ed Frank
print(bigList[-3:-1])

# This will replace index 1 (Bob) with the value of "Babette"
# Remember that indexes start with 0,
#   so "1" would be the SECOND index position (Bob)
bigList[1] = "Babette"
# Adam Babette Charlie...
print (bigList)

# Replace index values #2 and #3
# Remember it stops before #4
bigList[2:4] = ["Camille", "Denise"]
# Adam Babette Camille Denise Ed Frank Greg
print (bigList)

# 7 items
print (len(bigList))
# Replace index position 1 with two list
bigList[1:2] = ["Becca", "Cagney"]
# ['Adam', 'Becca', 'Cagney', 'Camille', 'Denise', 'Ed', 'Frank', 'Greg']
print (bigList)
# Now 8 items
print (len(bigList))

# Insert a list item at index position 4
# It becomes the new index position 4; everything else is moved toward the end
bigList.insert(4, "Daphne")
# ['Adam', 'Becca', 'Cagney', 'Camille', 'Daphne', 'Denise', 'Ed', 'Frank', 'Greg']
print (bigList)
# 9
print (len(bigList))