Chained Sequences
No account is required. Learn the material, try the examples, and mark it complete when you are ready to move on. Sign in with email only if you want to save progress across devices.
Lists within a list
So far, we have discussed lists, tuples, dictionaries, sets as a sequence.
But we can chain these data types together to create say, a list within a list, list within a tuple and so on.
list1 = list(range(4))
list1[0, 1, 2, 3]list2 = ["one", "two", "three", "four"]
list2['one', 'two', 'three', 'four']We have the append method to append anything inside a list. Lets see what happens when we append a list to another list.
list1.append(list2)list1[0, 1, 2, 3, ['one', 'two', 'three', 'four']]list1[0]0list1[-1]['one', 'two', 'three', 'four']As we can see, the last element of the list1 is the list2 itself. We may or may not want this behaviour.
What if our objective was to add just the elements together
list3 = list(range(4))
list3[0, 1, 2, 3]list4 = ["one", "two", "three", "four"]
list4['one', 'two', 'three', 'four']list3.extend(list4)list3[0, 1, 2, 3, 'one', 'two', 'three', 'four']In this case, notice that individual elements from the list4 are added inside the list3.
list3[-1]'four'list1[-1]['one', 'two', 'three', 'four']list1[0, 1, 2, 3, ['one', 'two', 'three', 'four']]list3[0, 1, 2, 3, 'one', 'two', 'three', 'four']Indexing
list1[0, 1, 2, 3, ['one', 'two', 'three', 'four']]list1[0]0list1[-1]['one', 'two', 'three', 'four']list1[-1][0]'one'Notice that after retrieving last element from the list1, we are retrieving first element inside the inner list.
list1[-1][1]'two'list1[-1][2]'three'list1[-1][3]'four'Tuple within a list
Lets create a tuple within a list
list5 = [1, 2, 3, (7,8,9)]list5[1, 2, 3, (7, 8, 9)]list5[-1](7, 8, 9)Notice that the last element of list is a tuple.
We remember that once a tuple is created, we cannot change the tuple elements. Although, we can reference that value.
list5[-1][0]7list5[-1][1]8list5[-1][2]9Dictionary inside a list
list6 = [1, 2, 3, {"Name": "Tickles", "Age": 29}]
list6[1, 2, 3, {'Name': 'Tickles', 'Age': 29}]list6[-1]{'Name': 'Tickles', 'Age': 29}Last element inside the list is a dictionary, and we index dictionaries by keys
list6[-1]["Name"]'Tickles'list6[-1]["Age"]29So on, we can create lists inside tuples, and vice versa. We can create dictionaries inside tuples or lists, or we could create lists inside a dictionary.
This is one of the most important topic to understand, but it comes with time and practice. When we reach the module numpy and pandas, you'll see how useful chaining different data types are.
Finished this lesson?
Keep your place here, or save it across devices with an email link.
Saved in this browser. Save progress with email →