Tuples Flashcards
What is a Tuple
- A tuple is an immutable sequence of Python objects
- Tuples are also comparable and hashable
ex: t= (‘a’,’b’,’c’,’d’)
time complexity: 0(1)
space complexity O(n)
how do we access elements in tuples
tuples can be accessed with brackets: []
ex: myTuple[2] or myTuple[-2]
The - int looks from the end of the tuple.
How are tuples saved in memory
Tuples are saved in memory continuously
How do you access a portion of a tuple
you can access a portion with slicing the data
ex: myTuple[1:3]
the index three is not included. 1 and 2 are.
How to traverse tuple
Use a for loop
ex: for i in myTuple:
print(i)
or
for i in range(len(newTuple)):
print(newTuple[i)
time complexity is O(n)
How do you check if an element is in a tuple?
you can use the in
operator to test if a value is in the.
ex: ‘x’ in myTuple
Different ways to search for a element in tuple
You can search with a looping function.
how do you concatenate tuples together.
you can use the + button to combine tuple
newTuple = tuple1 + tuple2
How to repeat the values in a tuple?
- opreator
ex myTuple * 2: this will take the values and repeat them once.
how to count how many times a value is in a tuple
count method
myTuple.count(‘a’)
How to find the index of a value in a tuple
find method
ex myTuple.index(4) this will find the first index in the tuple.
what function turns a list into a tuple
tuple()
ex: tuple([1,2,3,4)
When to use tuples and not lists
- tuples are not multiple
- Iterating rhrough a tuple is faster than with list
3 Tuples that contain immutable elements can be used as a key for a distonary - if you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected
- Generaly use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.