There are 4 built-in collection data types (arrays) in Python and each of them has their own uniqueness.
Lists are used to store multiple values in a single variable. A list can store multiple variables with multiple data types, including another collection data type.
Syntax:
list_name1 = [] #empty list list_name2 = [3, "hello", 22.5, [True, False]]
To access a list's element, we need to refer to its index number. Index number 0 is for the first element, index number 1 is for the second element, and so on. We can also use index -1 for the last element, -2 for the second last element, and so on.
Syntax: list_name[index_number] = new_value
Example:
myNumber[0] = 10
If the list is still empty, then the system will be an error, so make sure that you use the syntax only to change the list with an available element.
Example:
myNumber= [25, 50, 75, 100]; myNumber[0] = 30; #change the value 25 to 30 #myNumber will contain 30,50,75,100 now
To access elements from a list only from range a to b or elements
with index a until index b-1,
we can use the syntax list_name[a:b]. If the a is not specified, then by default, Python will
start at index 0. If b is not specified, then by default, Python will stop at the last element.
We can also use negative index here.
Example:
myList = ["alpha", "beta", "delta", "gamma", "epsilon", "theta"] print(myList[1:4]) print(myList[:4]) print(myList[1:]) print(myList[-4:-1])
Output:
['beta', 'delta', 'gamma']
['alpha', 'beta', 'delta', 'gamma']
['beta', 'delta', 'gamma', 'epsilon', 'theta']
['delta', 'gamma', 'epsilon']
We can also use the len()
function to return the size of a list or the amount of the elements in the list.
Syntax: len(list_name)
We can also change tuple into a list or initialize a list by using the list() function.
Syntax: list_name = list(("apple", "banana", "cherry"))
List has many built-in functions. Here are some of the commonly used ones:
insert() Example:
myList = ["alpha", "beta", "delta", "gamma"] myList.insert(2,"epsilon") #epsilon will become the third element
append() append().
The element that is appended will automatically be added as the last element in a list.
Example:
myList = ["gamma"] myList.append("epsilon") #myList will become ["gamma", "epsilon"]
remove() remove() is used to remove the specified element of a list.
Example:
myList = ["alpha", "beta", "delta", "gamma"] myList.remove("delta") #myList will become ["alpha", "beta", "gamma"]
pop() pop() is used to remove elements of a specified index. If we don't specify
the index of the pop() function, then it will automatically remove the last
element of a list. Additionally, we can store the element that we pop in another variable.
Example:
myList = ["alpha", "beta", "delta", "gamma"] myList.pop() #myList will become ["alpha", "beta", "delta"] popped = myList.pop(1) #pop beta #popped will contain beta and #myList will become ["alpha", "delta"]
del del is also used to remove elements of a specified index, but
it will delete it permanently (can't be stored in another variable).
del can also delete a list completely by using the syntax
del list_name .
Example:
myList = ["alpha", "beta", "delta", "gamma"] del myList[0] #myList will become ["beta", "delta", "gamma"]
clear() clear() is used to clear all elements in a list, so that the list will become empty.
Example:
myList = ["alpha", "beta", "delta", "gamma"] myList.clear() #myList will become []
sort() sort() is used to sort the list alphanumerically, ascending, by
default. If we want to sort it descending, then we just need to type reverse=True
inside the brackets.
Example:
myList = ["alpha", "gamma", "delta", "beta"] myList.sort() #myList will become ["alpha", "beta", "delta", "gamma"] myList.sort(reverse=True) #myList will become ["gamma", "delta", "beta", "alpha"]
copy() list2 = list1 as list2
will only be a reference to list1. To avoid this, we use the copy() function.
Example:
myList = ["alpha", "beta", "delta", "gamma"] myList2 = myList.copy() #myList will become ["alpha", "beta", "delta", "gamma"] #myList2 will also become ["alpha", "beta", "delta", "gamma"]
extend() extend() function or the operator +
Example:
myList = ["alpha", "beta"] myList2 = ["delta"] myList.extend(myList2) #myList will become ["alpha", "beta", "delta"] result = myList + myList2 #result will become ["alpha", "beta", "delta", "delta"]
Tuples are also used to store multiple elements in a single variable. The main difference between a tuple and a list is that a tuple is unchangeable.
Syntax:
tuple_name1 = () #empty tuple tuple_name2 = (3, "hello", 22.5, [True, False]) tuple_name3 = (1,) #if we want to make a tuple with 1 element, we have to put a comma
To access a tuple's element, we need to refer to its index number. Index number 0 is for the first element, index number 1 is for the second element, and so on. We can also use index -1 for the last element, -2 for the second last element, and so on.
Syntax: tuple_name[index_number]
Note that we can't change tuple's element. If we want to change it, we have to
change the whole tuple (redefine the tuple).
We can also use the len()
function to return the size of a tuple or the amount of the elements in the tuple.
Syntax: len(tuple_name)
We can also change a list into a tuple or initialize a tuple by using the
tuple() function.
Syntax: tuple_name = tuple(list_name)
To access elements from a tuple only from range a to b or elements
with index a until index b-1,
we can use the syntax tuple_name[a:b]. If the a is not specified, then by default, Python will
start at index 0. If b is not specified, then by default, Python will stop at the last element.
We can also use negative index here.
Example:
mytuple = ("alpha", "beta", "delta", "gamma", "epsilon", "theta") print(mytuple[1:4]) print(mytuple[:4]) print(mytuple[1:]) print(mytuple[-4:-1])
Output:
('beta', 'delta', 'gamma')
('alpha', 'beta', 'delta', 'gamma')
('beta', 'delta', 'gamma', 'epsilon', 'theta')
('delta', 'gamma', 'epsilon')
+ OperatorThe + operator can be used to join tuples.
Example:
myTuple = ("alpha", "beta") myTuple2 = ("delta",) result = myTuple + myTuple2 #result will become ("alpha", "beta", "delta")
* OperatorThe * operator can be used to multiply or duplicate the elements inside the tuple.
Example:
myTuple = ("alpha", "beta") myTuple = myTuple * 2 #result will become ("alpha", "beta", "alpha", "beta")
count() functioncount() is used to return number of occurrences that a value has in a tuple.
Example:
myTuple = ("alpha", "beta", "alpha") alpha_count = myTuple.count("alpha") #alpha_count will be 2
Sets are also used to store multiple elements in a single variable. A set is unordered, unchangeable, and unindexable, and duplicates are not allowed. But, we can still add and remove items in sets unlike in tuples.
Syntax:
set_name1 = {} #empty set set_name2 = {3, "hello", 22.5, [True, False]} #1 and True are considered the same in sets. #0 and False are also considered the same in sets.
Unlike lists and tuples, we can't access elements of a set by referring to its index number because sets are unordered. The only way to access the elements of a set is using the for loop.
Syntax:
for item in set_name: #code block
We can also use the len()
function to return the size of a set or the amount of the elements in the set.
Syntax: len(set_name)
Below are some Python built-in functions for sets.
add() add() is used to add an element to the set.
Example:
mySet = {"alpha", "beta", "delta", "gamma"} mySet.add("epsilon") #mySet will become {'gamma', 'delta', 'alpha', 'epsilon', 'beta'} #Note that order is not important in set
update() update() is used to update the sets by adding any iterable (can be sets, lists, etc).
Example:
mySet = {"alpha", "beta"} myList = ["delta", "gamma"] mySet.update(myList) #mySet will become {'beta', 'alpha', 'delta', 'gamma'}
remove() or discard() remove() or discard() is used to remove the specified element of a set. The difference is
discard() will not raise an error when the item to remove is not exist.
Example:
mySet = {"alpha", "beta", "delta", "gamma"} mySet.remove("delta") mySet.discard("gamma") #mySet will become {'beta', 'alpha'}
del del is used to delete a set completely by using the syntax:
del set_name
clear() clear() is used to clear all elements in a set, so that the set will become empty.
Example:
mySet = {"alpha", "beta", "delta", "gamma"} mySet.clear() #mySet will become empty
union() union() returns a new set with all items from both sets.
Example:
mySet = {"alpha", "beta"} mySet2 = {"beta", "delta", "gamma"} result = mySet.union(mySet2) #result will become {'gamma', 'delta', 'beta', 'alpha'}
intersection() intersection() method will return a new set, that only contains the
items that are present in both sets.
Example:
mySet = {"alpha", "beta"} mySet2 = {"beta", "delta", "gamma"} result = mySet.intersection(mySet2) #result will become {'beta'}
symmetric_difference() symmetric_difference() method will return a new set, that contains
only the elements that are not present in both sets.
Example:
mySet = {"alpha", "beta"} mySet2 = {"beta", "delta", "gamma"} result = mySet.symmetric_difference(mySet2) #result will become {'gamma', 'delta', 'alpha'}
Dictionaries are used to store data values in key:value pairs.
The key has to be an immutable object.
Syntax:
dict_name1 = {} #empty dictionary dict_name2 = {key1 : value1, key2 : value2, key3 : value3}
Unlike the other collection data types, we have to access an element of a dictionary by using its keys.
Syntax:
dict_name2 = {"name": "Mega", "age" : 18, "gender" : "female"} print(dict_name2["name"]) #the output will be Mega
If we access a key that is still not available in the dictionary, then the new key
and new value will automatically be appended to the dictionary. If the key is available,
then we can change the value.
Syntax: dict_name[key] = new_value
We use dict_name.keys() to access the keys in a dictionary,
dict_name.values() to access the values in a dictionary, and
dict_name.items() to access keys and values in a dictionary.
We can also use the len()
function to return the size of a dictionary or the amount of the elements in the dictionary.
Syntax: len(dict_name)
Below are some Python built-in functions to handle dictionary.
del del is used to delete a a dictionary keys
and values by specifying its key.
Example:
dict_name2 = {"name": "Mega", "age" : 18, "gender" : "female"} del dict_name2["name"] #dict_name2 will become {"age" : 18, "gender" : "female"}
clear() clear() is used to clear all elements in a dictionary, so that it will become empty.
Example:
dict_name2 = {"name": "Mega", "age" : 18, "gender" : "female"} dict_name2.clear() #dict_name2 will become {}
pop() and popitem() pop() is used to remove elements of a specified key. Meanwhile,
popitem() is used to remove the last item in a dictionary.
Additionally, we can store the element that we pop in another variable.
Example:
dict_name2 = {"name": "Mega", "age" : 18, "gender" : "female"} dict_name2.pop("name") #dict_name2 will become {'age': 18, 'gender': 'female'} popped = dict_name2.popitem() #pop gender:female #popped will contain ('gender', 'female') and #dict_name2 will become {'age': 18}
copy() copy() is used to make a duplicate of a dictionary. We can also
use the dict() keyword to make a copy of a dictionary
Example:
dict_name2 = {"name": "Mega", "age" : 18, "gender" : "female"} myDict = dict_name2.copy() thisDict = dict(dict_name2) #Three of them will have the same value, that is #{"name": "Mega", "age" : 18, "gender" : "female"}
Strings can be defined by using single quote or double quote and it is considered as a collection of character. You can assign multiline strings by using three quotes. It can be three single quotes or three double quotes.
Syntax:
string1 = """ some random text over here multiline """ string2 = "Hello!" string3 = 'world'
String in Python is treated as an array, so we can access its elements or characters by referring to its index number. Index number 0 is for the first element, index number 1 is for the second element, and so on. We can also use index -1 for the last element, -2 for the second last element, and so on.
Syntax: string_name[index_number]
We can also use the len()
function to return the the length of a string or the amount of the characters in the string.
Syntax: len(string_name)
To access elements from a string only from range a to b or elements
with index a until index b-1,
we can use the syntax string_name[a:b]. If the a is not specified, then by default, Python will
start at index 0. If the a is not specified, then by default, Python will
start at index 0. If b is not specified, then by default, Python will stop at the last element.
We can also use negative index here.
Example:
myString = "hello world" print(myString[1:4]) print(myString[:4]) print(myString[1:]) print(myString[-4:-1])
Output:
ell
hell
ello world
orl
+ OperatorThe + operator can be used to concatenate strings.
Example:
myString1 = "hello" myString2 = "world" result = myString1 + myString2 #result will be helloworld
* OperatorThe * operator can be used to multiply or duplicate the string.
Example:
myString1 = "hello" result = myString1 * 2 #result will be hellohello
We can use lower() to make all of the characters in string become lowercase,
upper() to make all of the characters in string become uppercase,
capitalize() to capitalize the first character in a sentence, and
strip() to remove white space before/after the actual text.
Example:
myString1 = " heLLo wORld." myString2 = myString1.strip() print(myString2) print(myString2.capitalize()) print(myString2.lower()) print(myString2.upper())
Output:
heLLo wORld.
Hello world.
hello world.
HELLO WORLD.