Tuples and more Flashcards
What makes a tuple different from a list?
A tuple is immutable
Tuples are unchangeable and always in the same order
What do you need to add if you only have one item in a tuple?
A coma
tuple = (‘one’,)
What constructor do you use to make something into a tuple?
tuple()
What is an array?
linear data structure
There are 4 array like structures in python
Must be same data type to be an array technically.
Arrays are indexed
Show a way to change a tuple item for:
x = (‘apple’, ‘banana’, ‘cherry’)
y = list(x)
y[1] = ‘kiwi’
x = tuple(y)
Show a way to add orange to the below
x = (‘apple’, ‘banana’, ‘cherry’)
y = list(x)
y.append(‘orange’)
x = tuple(y)
Add two tuples together
thistuple = (“apple”, “banana”, “cherry”)
y = (“orange”,)
thistuple += y
What does packing mean
What does unpacking mean
ie: packing a tuple
assigning values to it
extracting values back into variables.
So if you have the list fruits (like below) and you put it’s contents into separate variables (like below) then you just unpacked the list.
fruits = (“apple”, “banana”, “cherry”)
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Using the below tuple, place it’s elements into 3 variables, the last variable should contain the remaining elements in a list
tup = (‘apple’, ‘blueberry’, ‘grape’, ‘banana’)
(red, blue, *pellow) = tup
Using the below tuple, put the first and last element into a respective variable, throw the ones in the middle into their own variable
tup = (‘apple’, ‘blueberry’, ‘kiwi’, ‘grape’, ‘banana’)
(red, *fruit, yellow) = tup
Double all elements of the below tuple:
tup = (‘apple’, ‘blueberry’, ‘kiwi’, ‘grape’, ‘banana’)
mytup = tup * 2
Using the below tuple, show how many times ‘apple’ was used.
Show what index apple is in
tup = (‘apple’, ‘blueberry’, ‘kiwi’, ‘grape’, ‘apple’)
tup.count(‘apple’)
tup.index(‘apple’)
Name the four principles of a {set}
Unordered
Unchangeable
- you can’t change items, but you can add and remove.
Unindexed
No duplicates
What elements are considered exactly the same when placed in a set?
True/1
False/0
So if they’re both in a set together one will be deleted
Using the below set, add ‘orange’ to it
thisset = {“apple”, “banana”, “cherry”}
We don’t want ‘orange’ anymore… take it out NOW
thisset.add(‘orange’)
thisset.remove(‘orange’)
thisset.discard(‘orange’)
thisset.pop() <- might get it, might not