L 3-Python Collections
L 3-Python Collections
There are four collection data types in the Python programming language:
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data,
the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the
list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in
a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Example
Using the list() constructor to make a List:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
Negative indexing means start from the end
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not
included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including,
"kiwi":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Example
This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
The del keyword also removes the specified index:
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Python Tuples
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data,
the other 3 are List, Set, and Dictionary, all with different qualities and usage.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
Example
Using the tuple() method to make a tuple:
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Add Items
Since tuples are immutable, they do not have a build-in append() method, but
there are other ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can
convert it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want
to add one item, (or many), create a new tuple with the item(s), and add it to
the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
use the same workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing"
a tuple:
Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")
But, in Python, we are also allowed to extract the values back into variables.
This is called "unpacking":
Example
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
print(green)
print(yellow)
print(red)
Note: The number of variables must match the number of values in the tuple, if
not, you must use an asterisk to collect the remaining values as a list.
Python Sets
In Python, a Set is an unordered collection of data types that is iterable,
mutable and has no duplicate elements. The order of elements in a set is
undefined though it may consist of various elements. The major advantage of
using a set, as opposed to a list, is that it has a highly optimized method for
checking whether a specific element is contained in the set.
Creating a Set
# Creating a Set
set1 = set()
print(set1)
print(set1)
String = 'GeeksForGeeks'
set1 = set(String)
print(set1)
print(set1)
Output
Initial blank Set:
set()
Set with the use of String:
{'e', 'r', 'G', 's', 'F', 'k', 'o'}
Python3
# a List of Numbers
print(set1)
print(set1)
Output
Set with the use of Numbers:
{1, 2, 3, 4, 5, 6}
Python3
my_set = {1, 2, 3}
print(my_set)
Output
{1, 2, 3}
# Creating a Set
set1 = set()
print(set1)
set1.add(8)
set1.add(9)
set1.add((6, 7))
# using Iterator
set1.add(i)
print(set1)
Output
Initial blank Set:
set()
Python3
set1.update([10, 11])
print(set1)
Output
Set after Addition of elements using Update:
{4, 5, (6, 7), 10, 11}
Accessing a Set
# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)
# for loop
for i in set1:
# using in keyword
print("Geeks" in set1)
Output
Initial set
{'For', 'Geeks'}
Elements of set:
For Geeks True
Removing elements from the Set
Elements can be removed from the Set by using the built-in remove() function
but a KeyError arises if the element doesn’t exist in the set. To remove
elements from a set without KeyError, use discard(), if the element doesn’t exist
in the set, it remains unchanged.
Python3
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
print(set1)
set1.remove(5)
set1.remove(6)
set1.discard(8)
set1.discard(9)
print(set1)
set1.remove(i)
print(set1)
Output
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Pop() function can also be used to remove and return an element from the set,
but it removes only the last element of the set.
Note: If the set is unordered then there’s no such way to determine which
element is popped by using the pop() function.
Python3
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
print(set1)
set1.pop()
print(set1)
Output
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
To remove all the elements from the set, clear() function is used.
Python3
#Creating a set
set1 = set([1,2,3,4,5])
print(set1)
set1.clear()
print(set1)
Output
Initial set:
{1, 2, 3, 4, 5}
Python3
# working of a FrozenSet
# Creating a Set
Fset1 = frozenset(String)
print(Fset1)
# No parameter is passed
print(frozenset())
Output
The FrozenSet is:
frozenset({'o', 'G', 'e', 's', 'r', 'F', 'k'})
Empty FrozenSet:
frozenset()
Python3
my_set = set(my_list)
my_str = "GeeksforGeeks"
my_set1 = set(my_str)
my_set2 = set(my_dict)
Output
my_list as a set: {1, 2, 3, 4, 5, 6}
my_str as a set: {'f', 'G', 'r', 'o', 's', 'k', 'e'}
my_dict as a set: {1, 2, 3}
Set Methods
Function Description
another
Python Dictionary
Dictionary in Python is a collection of keys values, used to store data values
like a map, which, unlike other data types which hold only a single value as an
element.
Example of Dictionary in Python
Dictionary holds key:value pair. Key-Value is provided in the dictionary to make
it more optimized.
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Dictionary holds pairs of values, one
being the Key and the other corresponding pair element being its Key:value.
Values in a dictionary can be of any data type and can be duplicated, whereas
keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.
Python3
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dictionary can also be created by the built-in function dict(). An empty dictionary
can be created by just placing to curly braces{}.
# Creating an empty Dictionary
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Complexities for Creating a Dictionary:
Time complexity: O(len(dict))
Space complexity: O(n)
Nested Dictionary
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Adding elements to a Dictionary
Addition of elements can be done in multiple ways. One value at a time can be
added to a Dictionary by defining value along with the key e.g. Dict[Key] =
‘Value’. Updating an existing value in a Dictionary can be done by using the
built-in update() method. Nested key values can also be added to an existing
Dictionary.
Note- While adding a value, if the key-value already exists, the value gets
updated otherwise a new Key with the value is added to the Dictionary.
Python3
Dict = {}
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
# to a single Key
Dict['Value_set'] = 2, 3, 4
print(Dict)
Dict[2] = 'Welcome'
print(Dict)
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Geeks'}}}
Complexities for Adding elements in a Dictionary:
Time complexity: O(1)/O(n)
Space complexity: O(1)
Accessing elements of a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be
used inside square brackets.
Python3
# Creating a Dictionary
print(Dict['name'])
print(Dict[1])
Output:
Accessing a element using key:
For
Accessing a element using key:
Geeks
There is also a method called get() that will also help in accessing the element
from a dictionary. This method accepts key as argument and returns the value.
Complexities for Accessing elements in a Dictionary:
Time complexity: O(1)
Space complexity: O(1)
Python3
# Creating a Dictionary
# method
print(Dict.get(3))
Output:
Accessing a element using get:
Geeks
Python3
# Creating a Dictionary
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
Dictionary methods
clear() – Remove all the elements from the dictionary
copy() – Returns a copy of the dictionary
get() – Returns the value of specified key
items() – Returns a list containing a tuple for each key value pair
keys() – Returns a list containing dictionary’s keys
pop() – Remove the element with specified key
popitem() – Removes the last inserted key-value pair
update() – Updates dictionary with specified key-value pairs
values() – Returns a list of all the values of dictionary
Python3
# copy() method
dict2 = dict1.copy()
print(dict2)
# clear() method
dict1.clear()
print(dict1)
# get() method
print(dict2.get(1))
# items() method
print(dict2.items())
# keys() method
print(dict2.keys())
# pop() method
dict2.pop(4)
print(dict2)
# popitem() method
dict2.popitem()
print(dict2)
# update() method
dict2.update({3: "Scala"})
print(dict2)
# values() method
print(dict2.values())
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Python Arrays
Creating a Array
Array in Python can be created by importing array
module. array(data_type, value_list) is used to create an array with data type
and value list specified in its arguments.
Python3
# Creation of Array
print()
# printing original array
Output :
The new created array is : 1 2 3
The new created array is : 2.5 3.2 3.3
Complexities for Creation of Arrays:
Time Complexity: O(1)
Auxiliary Space: O(n)
Some of the data types are mentioned below which will help in creating an array
of different data types.
Adding Elements to a Array
Elements can be added to the Array by using built-in insert() function. Insert is
used to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given
index of array. append() is also used to add the value mentioned in its
arguments at the end of the array.
Python3
print()
# insert() function
a.insert(1, 4)
print()
print()
b.append(4.4)
for i in (b):
print()
Output :
Array before insertion : 1 2 3
Array after insertion : 1 4 2 3
Array before insertion : 2.5 3.2 3.3
Array after insertion : 2.5 3.2 3.3 4.4
Python3
# accessing element of array
Output :
Access element is: 1
Access element is: 4
Access element is: 3.2
Access element is: 3.3
Complexities for accessing elements in the Arrays:
Time Complexity: O(1)
Auxiliary Space: O(1)
Removing Elements from the Array
Elements can be removed from the array by using built-in remove() function but
an Error arises if element doesn’t exist in the set. Remove() method only
removes one element at a time, to remove range of elements, iterator is
used. pop() function can also be used to remove and return an element from
the array, but by default it removes only the last element of the array, to remove
element from a specific position of the array, index of the element is passed as
an argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the
searched element.
Python3
import array
# printing original array
print ("\r")
print (arr.pop(2))
print("\r")
Output:
The new created array is : 1 2 3 1 5
The popped element is : 3
The array after popping is : 1 2 1 5
The array after removing is : 2 1 5
Python3
# creating a list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l)
for i in (a):
Sliced_array = a[3:8]
print(Sliced_array)
Sliced_array = a[5:]
print(Sliced_array)
Sliced_array = a[:]
print(Sliced_array)
Output
Initial Array:
1 2 3 4 5 6 7 8 9 10
Slicing elements in a range 3-8:
array('i', [4, 5, 6, 7, 8])
import array
print ("\r")
print (arr.index(2))
print (arr.index(1))
Output:
The new created array is : 1 2 3 1 2 5
The index of 1st occurrence of 2 is : 1
The index of 1st occurrence of 1 is : 0
Time Complexity: O(n)
Auxiliary Space: O(1)
Updating Elements in a Array
In order to update an element in the array we simply reassign a new value to
the desired index we want to update.
Python3
import array
print ("\r")
arr[2] = 6
print()
arr[4] = 8
Output:
Array before updation : 1 2 3 1 2 5
Array after updation : 1 2 6 1 2 5
Array after updation : 1 2 6 1 8 5
Time Complexity: O(n)
Auxiliary Space: O(1)
References:
https://www.geeksforgeeks.org/python-sets/?ref=lbp
https://www.geeksforgeeks.org/python-dictionary/?ref=lbp