alist = [] # an empty list
blist = list() # an empty list
type(alist)
list
# creating lists with some elements of same type
list1 = [10, 20, 30, 40]
list2 = ['spam', 'bungee', 'swallow']
# lists with elements of different types
list3 = ["hello", 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
# print list
print(list3)
['hello', 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
# quickly create a list of range of numbers between 1 and 19
list4 = list(range(1, 20, 1))
print(list4)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# print multiple lists
print(alist, list1, list2, list3)
[] [10, 20, 30, 40] ['spam', 'bungee', 'swallow'] ['hello', 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
# Exercise: create a list of even numbers between 1 and 20 inclusive
# Exercise: create a list of odd numbers between 1 and 20 inclusive
# Exercise: create a list of numbers from 20 to 1 inclusive
# let's see what elements are in list1
list1
[10, 20, 30, 40]
# access an element, which one?
list1[0]
10
list3
['hello', 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
list3[2-2]
'hello'
# list index can be variable as well
index = 0
print(list3[index])
hello
# can you use float value as an index?
list3[1.0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-19-1fc6b2fe2f36> in <module>() 1 # can you use float value as an index? ----> 2 list3[1.0] TypeError: list indices must be integers or slices, not float
# how many elements are there in list3?
len(list3)
5
# what happens if you access an index equal to the size of the list
list3[5]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-21-207cd7e1c880> in <module>() 1 # what happens if you access an index equal to the size of the list ----> 2 list3[5] IndexError: list index out of range
list3
['hello', 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
# Exercise: access and print the last element of list3
# Can we use negative index?
# Can you guess the output of the following code?
print(list3[-1])
(1, 'uno')
# Exercise - access and print 'world' in list3
horsemen = ["war", "famine", "pestilence", ["death"]]
'death' in horsemen
False
'War' not in horsemen
True
["death"] in horsemen
True
list3
['hello', 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
# common technique; use for loop
for item in list3:
print(item)
hello 2.0 10 [10, ('hi', 'world'), 3.5] (1, 'uno')
for item in list3:
if isinstance(item, list) or isinstance(item, tuple):
for l in item:
print(l)
else:
print(item)
hello 2.0 10 10 ('hi', '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])
traversing using indices war famine pestilence death
print('traversing each element')
for ele in horsemen:
print(ele)
traversing each element war famine pestilence death
list2
['spam', 'bungee', 'swallow']
list3
['hello', 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
list4 = list2 + list3
list4
['spam', 'bungee', 'swallow', 'hello', 2.0, 10, [10, ('hi', 'world'), 3.5], (1, 'uno')]
[0]*10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a = [1, 2, 3]*4
a
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
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]]
# create a list of lower-case alphabets
alphas = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # add the rest...
alphas
['a', 'b', 'c', 'd', 'e', 'f', 'g']
# there's better way to create lists of all lowercase ascii
import string
alphas = list(string.ascii_lowercase)
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']
# convert string to list of characters
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']
# convert list to string by joining pairs of chars with a delimiter
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-51-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-62-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']
# even though a and b are two separate objects is still evaluates to True
a = 'apple'
b = 'apple'
a is b
True
# even though c and d are two separate objects is still evaluates to True
c = 10
d = 10
c is d
True
# what abut tuple?
e = (1, 2)
f = (1, 2)
print(e == f)
print(e is f)
True False
# What about lists?
l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(l1 == l2)
print(l1 is l2)
True False
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-98-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 = input('Enter 5 numbers separated by space: ')
Enter 5 numbers separated by space: 1 2 100 5
nums
'1 2 100 5'
nums = nums.split(' ')
nums
['1', '2', '100', '5']
intNums = []
for n in nums:
intN = int(n)
intNums.append(intN)
intNums
[1, 2, 100, 5]
intNums.sort()
intNums
[1, 2, 5, 100]
' '.join(intNums)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-94-0dd63a44d5ec> in <module> ----> 1 ' '.join(intNums) TypeError: sequence item 0: expected str instance, int found
strNum = []
for n in intNums:
strNum.append(str(n))
strNum
['1', '2', '5', '100']
strNum = ' '.join(strNum)
strNum
'1 2 5 100'
def getData(someList):# someList is formal parameter
for i in range(5):
a = int(input('enter a number: '))
someList.append(a)
alist = []
getData(alist) # alist is actual argument
enter a number: 1 enter a number: 10 enter a number: 4 enter a number: 6 enter a number: 90
# when formal parameter is updated, actual parameter is also updated
alist
[1, 10, 4, 6, 90]
def getMaxMin(alist):
m = max(alist)
minVal = min(alist)
return [m, minVal]
alist = list(range(-1000, 2000000))
print(getMaxMin(alist))
[1999999, -1000]
assert getMaxMin(alist) == [1999999, -1000]
atuple = (1, 2, 3)
alist = list(atuple)
print(alist)
[1, 2, 3]
btuple = tuple(alist)
print(btuple)
(1, 2, 3)
atuple == btuple
True
# eventhough the elements are equal; the types of two objects are not
print(atuple, alist)
print(atuple == alist)
(1, 2, 3) [1, 2, 3] False
a = [1, 2, 3]
b = a[:]
b[0] = 5
add_vectors(u, v)
that takes two lists of numbers of the same length, and returns a new list containing the sums of the corresponding elements of each. The following test cases must pass once the add_vectors is complete.def add_vectors(a, b):
pass
# test cases
assert add_vectors([1, 1], [1, 1]) == [2, 2], 'vectors not added correctly'
assert add_vectors([1, 2], [1, 4]) == [2, 6], 'vectors not added correctly'
assert add_vectors([1, 2, 1], [1, 4, 3]) == [2, 6, 4], 'vectors not added correctly'
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-125-f13d12d55331> in <module>() 1 # test cases ----> 2 assert add_vectors([1, 1], [1, 1]) == [2, 2], 'vectors not added correctly' 3 assert add_vectors([1, 2], [1, 4]) == [2, 6], 'vectors not added correctly' 4 assert add_vectors([1, 2, 1], [1, 4, 3]) == [2, 6, 4], 'vectors not added correctly' AssertionError: vectors not added correctly