Chapter 3: Tuples, Lists, and Dictionaries¶
In this chapter, we will explore three fundamental data structures in Python: Tuples
, Lists
, and Dictionaries
. Understanding these structures is crucial for data organization, storage, and manipulation in Python programming.
# A tuple of integers
my_tuple = (1, 2, 3)
# A tuple with mixed data types
mixed_tuple = ("Hello", 100, 1.5)
1.2 Accessing Tuple Elements using index¶
You can access elements of a tuple by using indexing, with the first element at index 0.
print(my_tuple[0]) # Output: 1
print(mixed_tuple[1]) # Output: 100
1 100
1.3 Sublist (equal to slice()
)¶
a_tuple = ('crazyit',20,5.6,'fkit',-17)
print(a_tuple[-3:-1])
print(a_tuple[1:-2])
print(a_tuple[::-1])
(5.6, 'fkit') (20, 5.6) (-17, 'fkit', 5.6, 20, 'crazyit')
2. Lists¶
Lists are mutable sequences, typically used to store collections of homogeneous items. Lists are defined by enclosing the elements in square brackets []
.
2.1 Creating a List¶
To create a list, you place all the items inside square brackets, separated by commas.
# A list of integers
my_list = [1, 2, 3, 4]
print(my_list)
# Adding elements to a list
my_list.append(5) # my_list is now [1, 2, 3, 4, 5]
print(my_list)
[1, 2, 3, 4] [1, 2, 3, 4, 5]
Python lists are also not type-restricted
my_list = [1,2,3,'a']
print(my_list)
my_list = [42, "hello", 3.14, [1, 2, 3], {'key': 'value'}, True]
print(my_list)
[1, 2, 3, 'a'] [42, 'hello', 3.14, [1, 2, 3], {'key': 'value'}, True]
2.2 Add elements to list¶
append()
: Adds a single element to the end of the list.my_list.append(element)
extend()
: Adds elements from an iterable (e.g.,list
,tuple
,string
) to the end of the list.my_list.extend([element1, element2])
insert()
: Inserts a given element at a specified position in the list.my_list.insert(index, element)
a_list = ['crazyit',20,-2]
a_list.append('fkit')
print(a_list)
['crazyit', 20, -2, 'fkit']
a_list.append(['a','b'])
print(a_list)
a_list.append(('a','b'))
print(a_list)
['crazyit', 20, -2, 'fkit', ['a', 'b'], ['a', 'b']] ['crazyit', 20, -2, 'fkit', ['a', 'b'], ['a', 'b'], ('a', 'b')]
b_list = ['a',30]
b_list.extend((-2,3.1))
print(b_list)
b_list = ['a',30]
b_list = b_list + [-2,3.1]
print(b_list)
['a', 30, -2, 3.1] ['a', 30, -2, 3.1]
b_list = ['a',30]
b_list = b_list + (-2,3.1)
print(b_list)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[27], line 2 1 b_list = ['a',30] ----> 2 b_list = b_list + (-2,3.1) 3 print(b_list) TypeError: can only concatenate list (not "tuple") to list
c_list = list(range(1,6))
print(c_list)
c_list.insert(3,'CRAZY')
print(c_list)
[1, 2, 3, 4, 5] [1, 2, 3, 'CRAZY', 4, 5]
c_list.insert(3,tuple('crazy'))
print(c_list)
[1, 2, 3, ('c', 'r', 'a', 'z', 'y'), 'CRAZY', 4, 5]
2.3 Remove elements from List¶
del statement
: This is not a function but a Python statement. It removes an item at a specific index or slices of elements from the list. It can also delete the list entirely.
my_list = ['a', 'b', 'c', 'd']
del my_list[1] # Removes 'b'
# Result: ['a', 'c', 'd']
print(my_list)
['a', 'c', 'd']
remove()
method: Removes the first occurrence of a value without needing to know its index. If the item is not found, it raises a ValueError
.
my_list = ['apple', 'banana', 'cherry']
my_list.remove('banana') # Removes 'banana'
# Result: ['apple', 'cherry']
print(my_list)
['apple', 'cherry']
pop()
method: Removes and returns an item at a given index (default is the last item). Without an argument, it removes the last item in the list.
my_list = [10, 20, 30, 40, 50]
removed_item = my_list.pop(2) # Removes 30
# Result: [10, 20, 40, 50], removed_item = 30
print(my_list)
[10, 20, 40, 50]
clear()
method: Empties the list, removing all items. The list remains, but it will have no content.
my_list = [1, 2, 3, 4, 5]
my_list.clear() # Clears the list
print(my_list)
[]
2.4 Other Popular Methods¶
count()
: Return number of occurrences of value.index()
: Return first index of value.pop()
: Remove and return item at index (default last). [Using list as Stack]reverse()
: Reverse the elements in a listsort()
: Sort the elements in a list
a_list = [2,30,'a',[5,30],30]
print(a_list.count(30))
print(a_list.count([5,30]))
2 1
a_list = [2,30,'a','b','crazyit',30]
print(a_list.index(30))
1
Search start from index 2
print(a_list.index(30,2))
5
print(a_list.index(30,2,4))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[37], line 1 ----> 1 print(a_list.index(30,2,4)) ValueError: 30 is not in list
Search start of index from 2 to 4
a_list = list(range(1,8))
a_list.reverse()
print(a_list)
[7, 6, 5, 4, 3, 2, 1]
a_list = [3,4,-2,-30,14,9.3,3.4]
a_list.sort()
print(a_list)
[-30, -2, 3, 3.4, 4, 9.3, 14]
b_list = ['Python','Swift','Ruby','Go','Kotlin','Erlang']
b_list.sort()
print(b_list)
['Erlang', 'Go', 'Kotlin', 'Python', 'Ruby', 'Swift']
Sort by given key func
b_list.sort(key = len)
print(b_list)
b_list.sort(key = len, reverse= True)
b_list
['Go', 'Ruby', 'Swift', 'Erlang', 'Kotlin', 'Python']
['Erlang', 'Kotlin', 'Python', 'Swift', 'Ruby', 'Go']
3. Shared property / methods of Tuple and List¶
3.1 Addition¶
a_tuple = ('crazyit',20,-1.2)
b_tuple = (127,'crazyit','fkit',3.33)
sum_tuple = a_tuple + b_tuple
print(sum_tuple)
print(a_tuple)
print(b_tuple)
('crazyit', 20, -1.2, 127, 'crazyit', 'fkit', 3.33) ('crazyit', 20, -1.2) (127, 'crazyit', 'fkit', 3.33)
print(a_tuple + (-20,-30))
('crazyit', 20, -1.2, -20, -30)
a_list = [20,30,50,100]
b_list = ['a','b','c']
sum_list = a_list + b_list
print(sum_list)
print(a_list + ['fkit'])
[20, 30, 50, 100, 'a', 'b', 'c'] [20, 30, 50, 100, 'fkit']
3.2 Multiply¶
mul_tuple = a_tuple * 3
print(mul_tuple)
('crazyit', 20, -1.2, 'crazyit', 20, -1.2, 'crazyit', 20, -1.2)
a_list = [30,'Python',2]
mul_list = a_list * 3
print(mul_list)
[30, 'Python', 2, 30, 'Python', 2, 30, 'Python', 2]
Example for adding ending of date
order_endings = ('st','nd','rd')\
+ ('th',) * 17 + ('st','nd','rd')\
+ ('th',) * 7 + ('st',)
print(order_endings)
('st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st')
day = input("please enter a date(1-31)")
day_int = int(day)
print(day + order_endings[day_int -1])
28th
3.3 Query elements use in
¶
a_tuple = ('crazyit',20,-1.2)
print(20 in a_tuple)
print(1.2 in a_tuple)
print('fkit' not in a_tuple)
True False True
3.4 Statistics¶
len()
max()
min()
a_tuple = (20,10,-2,15.2,102,50)
print(max(a_tuple))
print(min(a_tuple))
print(len(a_tuple))
102 -2 6
b_list = ['crazyit','fkit','Python','Kotlin']
print(max(b_list))
print(min(b_list))
print(len(b_list))
fkit Kotlin 4
# A simple dictionary
my_dict = {"name": "Alice", "age": 25}
print(my_dict)
# Adding a new key-value pair
my_dict["city"] = "New York" # my_dict now includes "city": "New York"
print(my_dict)
{'name': 'Alice', 'age': 25} {'name': 'Alice', 'age': 25, 'city': 'New York'}
Key could be tuple but not list!
dict2 = {(20,30):'good',30:'bad'}
print(dict2)
# dict2 = {[20,30]:'good',30:'bad'}
# print(dict2)
{(20, 30): 'good', 30: 'bad'}
Transfer List to Dictionary
vegetables = [('celery',1.58),('brocoli',1.29),('lettuce',2.19)]
dict3 = dict(vegetables)
print(dict3)
{'celery': 1.58, 'brocoli': 1.29, 'lettuce': 2.19}
cars = [['BMW',8.5],['BENS',8.3],['AUDI',7.9]]
dict4 = dict(cars)
print(dict4)
{'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9}
4.2 Basic Usage of Dictionary¶
- Use key to
access
value - Use key to
add
key-value record - Use key to
delete
key-value record - Use key to
modify
key-value record - Use key to
search
key-value
scores = {'literature':89, 'Math': 92, 'English': 93}
print(scores['Math'])
92
del scores['English']
print(scores)
{'literature': 89, 'Math': 92}
print('literature' in scores)
print('gym' not in scores)
True True
4.3 Useful functions¶
clear()
cars
[['BMW', 8.5], ['BENS', 8.3], ['AUDI', 7.9]]
cars.clear()
print(cars)
[]
get()
: get values based on key
print(scores.get('Math'))
print(scores.get('gym'))
92 None
update()
print(scores)
scores.update({'History':89, 'English':91})
print(scores)
{'literature': 89, 'Math': 92} {'literature': 89, 'Math': 92, 'History': 89, 'English': 91}
items()
: get all key-value recordkeys()
: get all keysvalues()
: get all values
subjects = scores.items()
print(subjects)
print(type(subjects))
dict_items([('literature', 89), ('Math', 92), ('History', 89), ('English', 91)]) <class 'dict_items'>
kys = scores.keys()
print(type(kys))
print(kys)
<class 'dict_keys'> dict_keys(['literature', 'Math', 'History', 'English'])
vals = scores.values()
print(type(vals))
print(vals)
<class 'dict_values'> dict_values([89, 92, 89, 91])
pop()
and popitem()
print(scores)
print(scores.pop('English'))
print(scores)
{'literature': 89, 'Math': 92, 'History': 89, 'English': 91} 91 {'literature': 89, 'Math': 92, 'History': 89}
print(scores.popitem())
print(scores)
('History', 89) {'literature': 89, 'Math': 92}
k,v = scores.popitem()
print(k,v)
Math 92
4.3 setdefault() and fromkeys()¶
setdefault()
Return the value of given key, if given key not exist in the origin dictionary, would return the given value.fromkeys()
Create dictionary from given list, using the elements from list as keys
cars = {'BMW':8.5, 'BENS':8.3, 'AUDI':7.9}
print(cars.setdefault('PORSCHE',9.2))
print(cars)
9.2 {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9, 'PORSCHE': 9.2}
print(cars.setdefault('BENS',5.2))
print(cars)
8.3 {'BMW': 8.5, 'BENS': 8.3, 'AUDI': 7.9, 'PORSCHE': 9.2}
a_dict = dict.fromkeys(['a','b'])
print(a_dict)
{'a': None, 'b': None}
b_dict = dict.fromkeys((13,17))
print(b_dict)
{13: None, 17: None}
c_dict = dict.fromkeys((13,17),'good')
print(c_dict)
{13: 'good', 17: 'good'}
4.4 Using dictionary to format string¶
temp = 'book name is %(name)s, price is %(price)06.2f, published by %(publish)s'
book = {'name':'Crazy Python','price':78.9,'publish':'who cares'}
print(temp % book)
book name is Crazy Python, price is 078.90, published by who cares
book = {'name':'Crazy JAVA','price':88.9,'publish':'I do not know'}
print(temp % book)
book name is Crazy JAVA, price is 088.90, published by I do not know