In computer programming, a collection is a grouping of some variable number of data items (possibly zero) that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion. [1]
This page provides syntax for different types of collections and data structures in Python (arrays, sets, dictionaries, etc.). Each section includes an example to demonstrate the described methods
Arrays
Arrays are ordered collections of elements. In Python they are automatically indexed (consecutively numbered) by an integer starting with 0.
Action
Syntax
New array (empty)
[]
Array with values (integers)
[1, 2, 3, 4, 5]
Array with values (string)
[“a1”, “ab2”, “c3”]
Array of numbers
list(range(1, 11))
Creating Array From String
Action
Syntax
Split string str by delimiter into words (e.g., space)
str.split(“ “)
Accessing Elements
Action
Syntax
Get length of array my_array
len(my_array)
Get first element of array my_array
my_array[0]
Get last element of array my_array
my_array[-1]
Get nth element of array my_array(e.g., 2)
my_array[1]
Check if element is in array
str in my_array
Adding and Removing Elements
Action
Syntax
Add element to end
my_array.append(str)
Remove element from end
my_array.pop()
Remove element from beginning
my_array.pop(0)
Add element to beginning
my_array.insert(0, str)
Sort and Unique
Action
Syntax
Sort array (will not change array itself)
sorted(my_array)
Sort array in place (will change array)
my_array.sort()
Get unique elements in array
list(set(my_array))
Compare Arrays
Action
Syntax
Intersection
set(my_array).intersection(your_array)
Union
set(my_array).union(your_array)
Input:
# Initialize the list and day variableday_array = ["Monday","Tuesday","Wednesday","Thursday","Friday"]day ="Thursday"# Get the array length and specific daysarray_length =len(day_array)array_first_day = day_array[0]# Indexing in Python starts at 0array_last_day = day_array[-1]# Python's negative indexing for last element# Print information about the arrayprint(f"Length of array: {array_length}")print(f"First day of week: {array_first_day}")print(f"Third day of week: {day_array[2]}")print(f"Last day of week: {array_last_day}")# Check if the day is in the arrayprint(f"{day} is in {day_array}: {day in day_array}")# Add "Sunday" to the beginning and "Saturday" to the endday_array.insert(0, "Sunday")day_array.append("Saturday")# Print each element in the arrayprint("Day of week:")for day in day_array:print(f" {day}")# Join array elements with ";" and printprint(f"Day of the week: {';'.join(day_array)}")# Sort the array and print againday_array.sort()print(f"Day of the week (sorted): {';'.join(day_array)}")
Output:
Length of array:5First day of week: MondayThird day of week: WednesdayLast day of week: FridayThursday isin ['Monday','Tuesday','Wednesday','Thursday','Friday']:TrueDay of week: Sunday Monday Tuesday Wednesday Thursday Friday SaturdayDay of the week: Sunday;Monday;Tuesday;Wednesday;Thursday;Friday;SaturdayDay of the week (sorted): Friday;Monday;Saturday;Sunday;Thursday;Tuesday;Wednesday
Sets
Sets are an unordered collection of unique elements.
Creating Sets
Action
Syntax
New set (empty)
[]
Set with values
my_set = {1, 2, 3, 4, 5}
Set with values
my_set = {"a1", "b2", "c3"}
Interacting With Sets
Action
Syntax
Get length of set my_set
len(my_set)
Check if value is in set
"str" in my_set
Add value
my_set.add("str")
Comparing Sets
Action
Syntax
Intersection
my_set.intersection(your_set)
Union
my_set.union(your_set)
Difference
my_set.difference(your_set)
Input:
color_set ={"red","yellow","blue"}color_set2 ={"red","orange","yellow"}print("Length of set:", len(color_set))print("Color Set 1")for color in color_set:print(" ", color)print("Color Set 2:", "---".join(color_set2))print("Intersection:", color_set.intersection(color_set2))print("Union:", color_set.union(color_set2))print("Difference:", color_set.difference(color_set2))print("Difference:", color_set2.difference(color_set))
Output:
Length of set:3Color Set 1 yellow blue redColor Set 2: yellow---orange---redIntersection:{'yellow','red'}Union:{'yellow','orange','blue','red'}Difference:{'blue'}Difference:{'orange'}
Dictionaries
Dictionaries are unordered collection of key-value pairs where the key serves as the index (“associative collection”). Similar to elements of a set, keys are always unique.
day_dict ={}day_length_dict ={}day_dict["Mon"]="Monday"day_dict["Tue"]="Tuesday"day_dict["Wed"]="Wednesday"day_dict["Thu"]="Thursday"day_dict["Fri"]="Friday"if"Wed"in day_dict:print(day_dict["Wed"])if"Sat"notin day_dict:print('no key "Sat"')print("print key-value pairs")for day in day_dict.keys():print(f" {day} = {day_dict[day]}")print("print values (sorted)")for day_value insorted(day_dict.values()):print(f" {day_value}")# get length of each value and keep track of lengthsfor day_value in day_dict.values(): day_length =len(day_value) day_length_dict[day_value]= day_lengthprint("print lengths")for day in day_length_dict.keys():print(f" {day} = {day_length_dict[day]}")print("print lengths in descending order")for length, day insorted(zip(day_length_dict.values(), day_length_dict.keys()), reverse=True):print(f" {day} = {length}")print("print lengths in ascending order")for length, day insorted(zip(day_length_dict.values(), day_length_dict.keys()), reverse=False):print(f" {day} = {length}")