Learn Python Data Containers in 3 Minutes: List/Set/Tuple
The List and its “brothers”: Tuple and Set

- List, Tuple and Set are all iterable.
- All of them can hold other types of data in Python
How to decide which one should be used among List/Tuple/Set?
- In most scenarios, the List would be the very first choice
Why?
The List is the most flexible container. The data in the list would be changeable and indexed, and the data in the list could be processed for other containers (e.g., tuple, set, dictionary).
[Notes for Manipulating List]list_eg.append(new_element)
# add a new_element in the end of list_eg list_eg = list_eg1 + list_eg2
# combine two lists and save the result as the list_eglist_eg = list_eg1.extend(list_eg2)
# merge list_eg1 with list_eg2 and save the result as the list_egindexof_element1 = list_eg.index(element1)
# get the index of the element1element1 = list_eg.pop(indexof_element1)
# remove the element1 from the list_eg and save itelement1 = list_eg[indexof_element1]
# return the element1 in list_eg by its indexsorted_list_eg = sorted(list_eg)
# sort all data in the list_eg in numerical or alphabetical and save it as a new list
Be aware…
The List container is inefficient when it runs in Python, and we should not consider it the panacea.
- When we need to keep some data immutable, the Tuple should be applied
Why?
The data stored in a tuple can not be altered, and the running time of the tuple is lower than that of the list. In addition, the data can be stored in pairs in a tuple.
[Notes for Manipulating Tuple]tuple_eg = zip(list_eg1, list_eg2)
# create tuple_eg with pairing dataelement_1, element_2 = tuple_eg[indexof_element_eg]
# unpack the element_eg from tuple_egfor index, element in enumerate(list_eg):
print(index, element)
# Create the tuple by the enumerate() method. This loop returns the position(index format) and the element in that position while looping
- When we need to check the data with set theory, the Set should be applied
[Notes for Manipulating Set]set_eg = set(list_eg)
# create set_eg by set() methodset_eg.add(new_element)
# add a single element into set_egset_eg1.update(seg_eg2)
# merge set_eg1 with set_eg2set_eg.discard(element1)
# remove the element1 from set_egset_eg.pop()
# randomly remove one element from set_egset_eg1.union(set_eg2)
set_eg1.intersection(set_eg2)
set_eg1.difference(set_eg2)
# "set theory" operation
Reference
[1] Data Types for Data Science in Python. DataCamp. (n.d.). Retrieved January 3, 2022, from https://app.datacamp.com/learn/courses/data-types-for-data-science-in-python