alist = [] # an empty list
blist = list() # an empty list
# elements with same type
list1 = [10, 20, 30, 40]
list2 = ['spam', 'bungee', 'swallow']
# elements with different types
list3 = ["hello", 2.0, 10, [10, ('world', 'world'), 3.5], (1, 'uno')]
print(list3[len(list3)-1])
(1, 'uno')
print(len(list3))
5
list4 = list(range(1, 20, 2))
print(list4)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(alist, list1, list2, list3)
[] [10, 20, 30, 40] ['spam', 'bungee', 'swallow'] ['hello', 2.0, 10, [10, ('world', 'world'), 3.5], (1, 'uno')]
list1
[10, 20, 30, 40]
list1[0]
10
list3
['hello', 2.0, 10, [10, ('world', 'world'), 3.5], (1, 'uno')]
list3[2-2]
'hello'
a = 0
print(list3[a])
hello
list3[1.0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-20-7447a11bec5d> in <module>() ----> 1 list3[1.0] TypeError: list indices must be integers or slices, not float
len(list3)
5
list3[10]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-23-2d72a649ac7f> in <module>() ----> 1 list3[10] IndexError: list index out of range
list3
['hello', 2.0, 10, [10, ('world', 'world'), 3.5], (1, 'uno')]
list3[3][1][1][-1]
'd'
list3[4][1]
horsemen = ["war", "famine", "pestilence", ["death"]]
print('death' in horsemen)
print('War' not in horsemen)
False True
["death"] == ["death"]
True
list3
# common technique; use for loop
for item in list3:
print(item)
hello 2.0 10 [10, ('world', 'world'), 3.5] (1, 'uno')
for lst in list3:
if isinstance(lst, list) or isinstance(lst, tuple):
for l in lst:
print(l)
else:
print(lst)
hello 2.0 10 10 ('world', 'world') 3.5 1 uno
horsemen = ["war", "famine", "pestilence", "death"]
for i in [0, 1, 2, 3]:
print(horsemen[i])
# better way to do the same thing?
war famine pestilence death
print("traversing using indices")
for i in range(len(horsemen)):
print(horsemen[i])
print('traversing each element')
for ele in horsemen:
print(ele)
traversing using indices war famine pestilence death traversing each element war famine pestilence death
list2
['spam', 'bungee', 'swallow']
list4 = list2+list3
list4
['spam', 'bungee', 'swallow', 'hello', 2.0, 10, [10, ('world', 'world'), 3.5], (1, 'uno')]
[0]*10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a = [1, 2, 3]*4
b = [a]*3
b
[[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3], [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]]
# 2-D list or matrix
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix)
[[1, 2], [3, 4], [5, 6]]
matrix
[[1, 2], [3, 4], [5, 6]]
# How do you replace 5 with 50 in matrix?
matrix[2][0] = 50
matrix
[[1, 2], [3, 4], [50, 6]]
#alphas = ['a', 'b', 'c', 'd', 'e', 'f', 'h']
# wait there's better way to create lists of all lowercase ascii
import string
alphas = list(string.ascii_lowercase)
alphas
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print(alphas[:])
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print(alphas[::3])
['a', 'd', 'g', 'j', 'm', 'p', 's', 'v', 'y']
print(alphas[1:3])
['b', 'c']
print(alphas[::-1])
['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
alphaList = list(string.ascii_lowercase)
alphaList
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
alphaStr = '|'.join(alphaList)
alphaStr
'a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z'
names = ["john", "David", "Alice"]
names[0] = "jake"
names
['jake', 'David', 'Alice']
# How to correct spelling of jake?
names[0][0]
'j'
names[0][0] = 'J'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-0442e9474c4b> in <module>() ----> 1 names[0][0] = 'J' TypeError: 'str' object does not support item assignment
names[0] = 'Jake'
names
['Jake', 'David', 'Alice']
alphas
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
alphas[:4] = ['A', 'B', 'C', 'D']
alphas
['A', 'B', 'C', 'D', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
alphas[:4] = []
alphas
['e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
alphas
['e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
del alphas[0]
alphas
['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
del alphas[26]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-16-80e1a19bb44c> in <module>() ----> 1 del alphas[26] IndexError: list assignment index out of range
alphas.index('z')
20
alphas.index(alphas[-1])
20
del alphas[1:3]
alphas
['f', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
indexOfZ = alphas.index('z')
del alphas[indexOfZ]
print(alphas)
['f', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y']
a = 'apple'
b = 'apple'
a is b
True
# What about lists?
l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(l1 == l2)
print(l1 is l2)
a = [1, 2, 3]
b = a
print(a is b)
print(a == b)
True True
b[0] = 10
print(a)
print(b)
[10, 2, 3] [10, 2, 3]
# How do you actually clone lists - do a deep copy?
c = a[:] # easy way shallow copy
d = a.copy() # shallow copy
import copy
e = copy.deepcopy(b)
c is a
False
d is a
False
b is e
False
help(list)
Help on class list in module builtins: class list(object) | list(iterable=(), /) | | Built-in mutable sequence. | | If no argument is given, the constructor creates a new empty list. | The argument must be an iterable if specified. | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(self, value, /) | Return self>value. | | __iadd__(self, value, /) | Implement self+=value. | | __imul__(self, value, /) | Implement self*=value. | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __reversed__(self, /) | Return a reverse iterator over the list. | | __rmul__(self, value, /) | Return value*self. | | __setitem__(self, key, value, /) | Set self[key] to value. | | __sizeof__(self, /) | Return the size of the list in memory, in bytes. | | append(self, object, /) | Append object to the end of the list. | | clear(self, /) | Remove all items from list. | | copy(self, /) | Return a shallow copy of the list. | | count(self, value, /) | Return number of occurrences of value. | | extend(self, iterable, /) | Extend list by appending elements from the iterable. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | insert(self, index, object, /) | Insert object before index. | | pop(self, index=-1, /) | Remove and return item at index (default last). | | Raises IndexError if list is empty or index is out of range. | | remove(self, value, /) | Remove first occurrence of value. | | Raises ValueError if the value is not present. | | reverse(self, /) | Reverse *IN PLACE*. | | sort(self, /, *, key=None, reverse=False) | Stable sort *IN PLACE*. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
a = []
a.append(1)
a.append(2)
a.append([2, 3])
a
[1, 2, [2, 3]]
a.extend([3, 4])
a
[1, 2, [2, 3], 3, 4]
a.append([5, 6])
a
[1, 2, [2, 3], 3, 4, [5, 6]]
a.insert(0, 'hi')
a
['hi', 1, 2, [2, 3], 3, 4, [5, 6]]
a.reverse()
a[0].reverse()
a
[[6, 5], 4, 3, [2, 3], 2, 1, 'hi']
a.sort()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-45-2ed0d7de6146> in <module>() ----> 1 a.sort() TypeError: '<' not supported between instances of 'int' and 'list'
blist = list(range(10, 0, -1))
blist
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
blist.sort()
print(blist)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
blist.sort(reverse=True)
blist
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
m = max(blist)
mI = blist.index(m)
print(mI)
0
min(blist)
1
print(blist.count(100))
0
nums = '1 2 100 5'
nums = nums.split(' ')
intNums = []
for n in nums:
intN = int(n)
intNums.append(intN)
intNums
[1, 100, 2, 5]
intNums.sort()
intNums
[1, 2, 5, 100]
alist = []
print(alist)
[]
def getData(someList):# someList is formal parameter
for i in range(5):
a = int(input('enter a number: '))
someList.append(a)
print(alist)
getData(alist) # alist is actual argument
[] enter a number: 1 enter a number: 2 enter a number: 3 enter a number: 4 enter a number: 5
alist
[1, 2, 3, 4, 5]
getData(alist)
enter a number: 10 enter a number: 20 enter a number: 30 enter a number: 40 enter a number: 50
alist
[1, 2, 3, 4, 5, 10, 20, 30, 40, 50]
def getMaxMin(alist):
m = max(alist)
minVal = min(alist)
return [m, minVal]
[1999999, -1000]
alist = list(range(-1000, 2000000))
print(getMaxMin(alist))
[1999999, -1000]
assert getMaxMin(alist) == [1999999, -1000]