Tuples and Lists Flashcards
Tuples
there are different data types: string, integer and float. These data types can all be contained in a tuple as follows:
concatenate tuples
tuple2 = tuple1 + (“hard rock”, 10)
tuple2
(‘disco’, 10, 1.2, ‘hard rock’, 10)
slicing tuples
tuple2[0:3]
‘disco’, 10, 1.2
sort tuples
RatingsSorted = sorted(Ratings)
RatingsSorted
[0, 2, 5, 6, 6, 8, 9, 9, 10]
Lists
Lists contain strings, floats and integers
L = [“Michael Jackson”, 10.1,1982,”MJ”,1]
L
[‘Michael Jackson’, 10.1, 1982, ‘MJ’, 1]
Use “extend” to add new elements to the list
L = [ “Michael Jackson”, 10.2]
L.extend([‘pop’, 10])
L
[‘Michael Jackson’, 10.2, ‘pop’, 10]
Use “append” to add one element
L = [ “Michael Jackson”, 10.2]
L.append([‘pop’, 10])
L
[‘Michael Jackson’, 10.2, [‘pop’, 10]]
Changing a list
A = ["disco", 10, 1.2] print('Before change:', A) A[0] = 'hard rock' print('After change:', A) Before change: ['disco', 10, 1.2] After change: ['hard rock', 10, 1.2]
Deleting an element in a list
print('Before change:', A) del(A[0]) print('After change:', A) before change: ['hard rock', 10, 1.2] After change: [10, 1.2]
split
‘hard rock’.split()
[‘hard’, ‘rock’]
clone a list
B = A[:]
B
[‘banana’, 10, 1.2]