Chapter 5 - data structures Flashcards
how to slice?
x[1:3] returns the substring from index 1 to index 2 (does not include 3rd)
what does this return?
myword = ‘help’
myword[-2:-1]
‘l’
what does this return?
w = ‘mannn’
print(myword[:2])
print(myword[2:])
ma
nnn
what happens?
w = ‘mann’
print([myword[:])
prints entire string
mann
x = “myy wordssss”
x[4:3]
what does this return?
’’
^empty string
what does this return?
x = “myy wordssss”
x[::2]
‘mywrss’
^skips every other index, due to jump of 2 in substring
what does this return?
x = “myy wordssss”
x[::-2]
‘ssdo y’
^indexes backwards in steps of 2
how to reverse real easy using step function?
x[::-1]
how would you concatenate a string to itself 3 times?
x*=3
create an empty list
ok = []
how to delete list elements w/o using del keyword?
set part of list x[0:2] = []
add 25 to the end of this list:
a = [1, 2, 4, 3, 2]
a += [25]
^can only add lists together, which is why 25 is in brackets
bob = “123456789”
bob[0:-1]
returns?
‘12345678’
what will this return:
numlist = [1, 2, 3, 4, 5, 6]
numlist[-1] = []
[1, 2, 3, 4, 5, []]
you need the colon operator to actually replace! (numlist-[-1:] = [])
what is the only way to index backwards using the [:]?
use negative steps, such as:
x[::-1]
what will the following return:
- iter(range(4))
- iter([1, 2, ‘4’, 8])
- iter(33)
<range_iterator at 0x7fb888bb480f0>
2.
<list_iterator at (stuff im too lazy to write)>
- TypeError: ‘int’ object is not iterably
what does range create?
creates an iterator of type range (though can be casted to list) ONE AT A TIME until
n-1 value of range(n) is reached
what will this return?
l = [1, 2, 3, 4, 5, 6]
l[::-1]
[6, 5, 4, 3, 2, 1]
true/false:
enumerate requires both an index and item iterator to be “used to its full potential”
false, if given only one iterator variable in a for loop will just set equal to a tuple (index, item)
tuple vs. list
tuples are IMMUTABLE, and are put in parentheses instead of colons OR just plain text like:
tuple1 = 1, 3
slicing, indexing, concatenation, and len methods are the same
how to create tuple with one entry
oneTup = (7,)
prints out (7,)
im told parentheses and comma are necessary, not sure abt the parentheses part bcz it worked :(
what type is returned if you index a tuple?
returns a tuple mytup = (3, 7, “m”, 20)
mytup[2:3]
returns (“m”,)
can a tuple be typecasted?
yes, to a list. also, can typecast lists and strings to tuples
packing vs. unpacking
packing = puts multiple values separated by commas into tuple
unpacking = setting equal amount of variables to left side of tuple so each gets assigned tuple elements in that order
unpacking ispossible for lists and strings too!