Python Collection Data Types

Learn how to process sequential data using collections: lists, tuples, sets, and dictionaries.

Collections

Python provides us with built-in collection data types given as follows:

  • List

  • Tuple

  • Set

  • Dictionary

List

A list is an ordered and mutable (i.e., an object whose value can change) collection of elements in Python. A list variable can store multiple items of different types. Python specifies lists using square brackets. Just like strings, we use positive and negative indexing to access any particular element or item in a list. The following code demonstrates the use of indexing for a list.

Press + to interact
item_list = ["backpack", "laptop", "ballpoint", "sunglasses"]
# Indexing list elements
print(item_list[2], '\n',
item_list[-3], '\n',
item_list[:3], '\n',
item_list[2:], '\n',
item_list[-3:-1], '\n',
item_list[-1:-4:-2], '\n',
item_list[-1:-4:2])

Lines 9 and 10 apply strides of -2 and 2 to item_list, respectively. The last line of the output results in an empty list because we specify a positive stride of 2 while moving from the starting index -1 to the ending index -4. Python provides numerous methods applicable to lists. The following code applies some of the methods to a list, namely fruits.

Press + to interact
fruits = ["apple", "orange", "guava"]
# Adding an element at the end of the list.
fruits.append('banana')
# Adding an element at a specified index.
fruits.insert(2, 'melon')
# Removing an existing element from the list. We get an error for a nonexistent element.
fruits.remove("guava")
# Copying list elements to a new list.
new_fruits = fruits.copy()
# Printing the results.
print('The original list:', fruits,
'\n\nThe copy of the original list:', new_fruits)
# Reversing the order of list elements.
fruits.reverse()
print('\nThe list in the reverse order:', fruits)
# Sorting list elements.
fruits.sort()
print('\nThe sorted list:', fruits)
# Clearing the list.
fruits.clear()
print('\nThe cleared list:', fruits)

  • Line 4: To add an item to the end of the list, use append(). For example, fruits.append('banana') inserts a new element, banana, to the end of an existing list, namely fruits.

  • Line 7: To add an item at the specified index, use insert(). For example, fruits.insert(2, 'melon') inserts a new element melon at index 2 to an existing list (fruits).

  • Line 10: To remove a specified item, use remove(). For example, fruits.remove("guava") removes the element guava.

  • Line 13: To copy the elements of a list, use copy(). For example, new_fruits = copy(fruits) copies all items of fruits to new_fruits.

  • Line 20: To reverse the elements of a list, use reverse(). For example, fruits.reverse() reverses the elements of the list (fruits).

  • Line 24: To sort the elements of a list, use sort(). For example, fruits.sort() rearranges items of fruits in ascending order. To sort in descending order, use fruits.sort(reverse=True).

  • Line 28: To clear a list, use clear().

Tuple

A tuple is an ordered and immutable collection of items. Python specifies tuples using round brackets. Once declared, we can’t alter the elements of a tuple. Tuples support positive, negative, and a range of indexing. The following code uses some methods applicable to Python tuples.

Press + to interact
# Creating a tuple and specifying its elements
my_tuple = ('Deep Learning', 'in', 'Python', 'Deep Learning')
# Counting the number of times a particular element appears in the tuple
print('The element \'Deep Learning\' appears', my_tuple.count("Deep Learning"), 'times at the index', my_tuple.index("Deep Learning"))
print('The element \'Deep\' appears', my_tuple.count("Deep"), 'times')
# We get an error if the tuple does not have the specified element
# mytuple.index("Deep") # uncomment this line to observe the output
# Trying to alter an element of a tuple
# my_tuple[1] = 'using' # uncomment this line to observe the output
# Negative indexing
print('\nThe element at index -1: ', (my_tuple[-1]))
# Converting a tuple to a list to make changes
list_from_tuple = list(my_tuple)
list_from_tuple[1] = 'using'
# Converting the list back to the tuple
my_tuple = tuple(list_from_tuple)
print(my_tuple)
# Deleting a tuple
del my_tuple
# print(my_tuple) # uncomment this line to observe the output
  • Line 5: This uses my_tuple.count("Deep Learning") to count the occurrence of the Deep Learning element in the tuple. The index() method gives the first index where it finds the specified value.

  • Line 9: This tries to find a non-existent tuple element that results in an error.

  • Line 12: This tries to alter a tuple element which results in an error.

  • Line 15: This demonstrates the use of negative indexing to return an element of a tuple.

  • Line 18: This converts a tuple to a list.

  • Line 22: This converts a list to a tuple.

  • Line 26: This deletes my_tuple.

Set

A set is an unindexed and unordered collection of items. Python sets don’t allow duplicate elements. Python specifies sets using curly brackets. Different functions of sets have been demonstrated in the following code.

Press + to interact
# Creating a set and specifying its elements
my_animals = {"tiger", "cat", "dog", "fox"}
print('Elements in the set =', my_animals)
# Adding a new element to an existing set
my_animals.add("lion")
print('Updated set after adding lion = ', my_animals)
# Adding multiple new elements to an existing set
my_animals.update(['sheep', 'goat', 'cow', 'goat'])
print('Updated set after adding multiple elements = ', my_animals)
# Removing set elements
my_animals.remove("tiger")
print('Updated set after removing tiger = ', my_animals)
my_animals.discard("goat")
print('Updated set after removing goat = ',my_animals)
# Uncomment the following line to observe the output
#my_animals[2]

Can you guess why the order of set elements is different than the order when the set is declared? The reason is that no index is linked to elements in a set because it’s an unordered collection. Since sets have unique elements, the element goat appears only once in the final set. Sets don’t support indexing. Try uncommenting the last line of the code above to observe the output. A set does not support item assignment because it doesn’t allow us to change its elements. However, the methods add and update add single and multiple elements to a set, respectively, as demonstrated in the code above.

Dictionary

A dictionary is a mutable, unordered, and indexed collection of items. A dictionary has a key : value pair for each of its elements. Dictionaries retrieve values when the keys are known. To create a dictionary, we use curly brackets. We put key : value elements inside these brackets where pairs are separated from others by commas. Keys in a dictionary are unique, immutable strings, numbers, or tuples. The values can be of any data type and can repeat. Square brackets refer to a key name to access a specified value of a dictionary. The following code creates a dictionary named my_dict and applies dictionary methods to it.

Press + to interact
# Declaring a dictionary
my_dict = {
"name" : "Deep Learning",
"purpose" : "Android Apps",
"year" : 2023
}
print("Displaying the key : value pairs for the specified dictionary:", my_dict, "\n")
# Accessing value for the key 'name'
print("Accessing value for the key name:", my_dict['name'], "\n")
# Accessing value for the key 'purpose' using the method get()
print("Accessing value for the key purpose using get(): ", my_dict.get('purpose'), "\n")
# A message: None is displayed if we try to access a nonexistent key
print("Accessing a non-existent key results:", my_dict.get('address'), "\n")
# Changing the value of an element by referring to its key
my_dict['name'] = "Deep Learning using TensorFlow"
print("Updated dictionary is:", my_dict, "\n")
# Printing dictionary keys and values separately
print(my_dict.keys(),
my_dict.values())
# Adding a new key : value pair to a dictionary
my_dict['Publisher'] = 'Educative'
print(' \nUpdated dictioanry is:', my_dict)
# Removing a key : value pair from a dictionary
my_dict.pop('year')
# del my_dict["year"] does the same job.
print(' \nUpdated dictionary is:', my_dict)
# The method clear() deletes all elements of a dictionary
my_dict.clear()
print('The dictionary is cleared: ', my_dict)
  • Line 19: This changes the value of an element by referring to its key.

  • Line 27: This adds a new element to a dictionary by specifying a new key and assigning it a value.

  • Line 31: This deletes an element from the dictionary using the pop() method.

  • Line 36: This deletes all elements of the dictionary using the clear() method.

The keyword del before the dictionary’s name removes the dictionary: del my_dict.

The following table summarizes collection data types.

Summary of Collection Data Types


List

Tuple

Set

Dictionary

Collection Type

Ordered data

Ordered data

Unordered data

Unordered data

Mutable

Mutable

Immutable

Mutable

Mutable

Represented Using

Square brackets [ ]

Parenthesis ( )

Curly brackets { }

Curly brackets as key-value pairs { key : value }

Duplicates

Allowed

Allowed

Not allowed

Allowed (keys should be unique)

Adding New Elements

Allowed

Not allowed

Allowed

New key-value pairs are allowed

Conclusion

In this lesson, we’ve covered Python collection data types. We’ve also discussed commonly used methods applicable to collections.