Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Python Collections (Arrays)

The document provides an overview of Python's collection data types: List, Tuple, Set, and Dictionary. Each type is described with its characteristics, methods, and examples of usage. Lists are ordered and changeable, Tuples are ordered and unchangeable, Sets are unordered and unindexed, and Dictionaries are unordered, changeable, and indexed.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Collections (Arrays)

The document provides an overview of Python's collection data types: List, Tuple, Set, and Dictionary. Each type is described with its characteristics, methods, and examples of usage. Lists are ordered and changeable, Tuples are ordered and unchangeable, Sets are unordered and unindexed, and Dictionaries are unordered, changeable, and indexed.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Python Collections (Arrays)

There are four collection data types in the Python


programming language:
List is a collection which is ordered and
changeable.
Allows duplicate members.
Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
Set is a collection which is unordered and
unindexed. No duplicate members.
Dictionary is a collection which is unordered,
changeable and indexed. No duplicate
members.
List
A list is a collection which is ordered and changeable. In Python
lists written with square brackets.
eg :thislist = ["apple", "banana", "cherry"]
 access the list items by referring to the index number.
eg:thislist[1]
 Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to
the second last item etc.
eg:thislist[-1]
 You can specify a range of indexes by specifying where to start and where to end the
range.
eg:thislist[2:5]
 To change the value of a specific item, refer to the index number.
eg:thislist[1] = "blackcurrant“
 You can loop through the list items by using a for loop.
eg:for x in thislist:
 To determine if a specified item is present in a list use the in keyword:
eg: if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
List
 To determine how many items a list has, use the len() method.
eg:len(thislist)
 To add an item to the end of the list, use the append() method:
eg: thislist.append("orange")
o/p: ['apple', 'banana', 'cherry', 'orange']
 To add an item at the specified index, use the insert method().
eg: thislist:insert(1, "orange")
o/p:['apple', 'orange', 'banana', 'cherry']
 There are several methods to remove items from a list:
* remove() method removes the specified item
eg:thislist.remove("banana")
* pop() method removes the specified index or the last item if
index is not specified.
* del keyword removes the specified index:eg del thislist[0]
* clear() method empties the list.
List
 There are ways to make a copy,
* use the built-in List method copy()
eg:thislist.copy()
o/p ['apple', 'banana', 'cherry']
*Another way to make a copy is to use the built-in method list()
eg:mylist = list(thislist)
 There are several ways to join, or concatenate, two or more lists
* easiest ways are by using the + operator. eg:list3 = list1 +
list2
* join two lists are by appending all the items from list2 into
list1, one by one.
eg:for x in list2:
list1.append(x)
* you can use the extend() method, which purpose is to add
elements from one list to another list
eg:list1.extend(list2)
List methods
Python has a set of built-in methods that you can use on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the
specified value
extend() Add the elements of a list (or any
iterable), to
the end of the current list
index() Returns the index of the first element
with
the specified value
List
insert() Adds an element at the specified
position
pop() Removes the element at the
specified
position
remove() Removes the item with the
specified value
reverse() Reverses the order of the list
sort() Sorts the list
Tuple

A tuple is a collection which is ordered and unchangeable.


In Python tuples are written with round brackets.
eg:thistuple = ("apple", "banana", "cherry“)

You can access tuple items by referring to the index number, inside square
brackets.
eg:thistuple[1]

Negative indexing means beginning from the end, -1 refers to the last item,-
2 refers to the second last item etc.
eg:thistuple[-1]

You can specify a range of indexes by specifying where to start and where to
end the range.
eg:thistuple[2:5]

Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
eg:x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
Tuple
 You can loop through the tuple items by using a for loop.
eg: for x in thistuple:
print(x)
 To determine if a specified item is present in a tuple use the in
keyword:
eg: if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
 To determine how many items a tuple has, use the len() method:
eg: len(thistuple)
 Once a tuple is created, you cannot add items to it. Tuples are
unchangeable.
eg:thistuple[3] = "orange“ # This will raise an
error
 To create a tuple with only one item, you have to add a comma after
the item, unless Python will not recognize the variable as a tuple.
eg: thistuple = ("apple",)
print(type(thistuple)) #class tuple

#NOT a tuple
thistuple = ("apple")
print(type(thistuple)) # class str
Tuple
 Tuples are unchangeable, so you cannot remove items
from it, but you can delete the tuple completely:
eg: thistuple = ("apple", "banana",
"cherry")
del thistuple
print(thistuple) #this will raise an
error because the tuple no longer exists
 To join two or more tuples you can use the + operator:
eg:tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
 It is also possible to use the tuple() constructor to make a
tuple.
eg:thistuple = tuple(("apple", "banana",
"cherry"))
# note the double round-brackets
Tuple Methods
Python has two built-in methods that you can
use on tuples.
Method Description
count() Returns the number of times a
specified value occurs in a
tuple
index() Searches the tuple for a
specified value and returns
the
position of where it was found
Set

A set is a collection which is unordered and unindexed.


In Python sets are written with curly brackets.
eg:thisset = {"apple", "banana", "cherry"}
 You cannot access items in a set by referring to an index,
since sets are unordered the items has no index.But you can loop
through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
eg: for x in thisset:
print(x)
 Check if "banana" is present in the set:
eg:print("banana" in thisset)
 Once a set is created, you cannot change its items, but you can add
new items.
* to add one item to a set use the add() method.
eg: thisset.add("orange")
Set
 to determine how many items a set has, use the len() method.
eg:print(len(thisset))
 to remove an item in a set, use the remove(), or the discard() method.
*using the remove() method
eg:thisset.remove("banana")
*using the discard() method:
eg: thisset.discard("banana")
*you can also use the pop() method,but this method will
remove the last item.
eg: x = thisset.pop()
 the clear() method empties the set:
eg: thisset.clear()
 add multiple items to a set, using the update() method
eg:thisset.update(["orange", "mango", "grapes"])

Set
The clear() method empties the set:
eg:thisset.clear()
 The del keyword will delete the set completely:
eg:del thisset
 There are several ways to join two or more sets in Python.
*using the union() method that returns a new set
containing all items from both sets,
eg:set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
* the update() method inserts the items in set2 into set1:
eg: set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
Set
 It is also possible to use the set() constructor to make a set.
eg:thisset = set(("apple", "banana", "cherry"))
# note the double round-brackets

Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the
set
copy() Returns a copy of the set
difference() Returns a set containing the difference
between two or more sets
difference_update() Removes the items in this set that are also included
in another, specified set
discard() Remove the specified item
Set
Method Description
intersection() Returns a set, that is the intersection of two
other sets
intersection_update() Removes the items in this set that are not
present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection
or
not
issubset() Returns whether another set contains this set
or
not
issuperset() Returns whether this set contains another set
or
not
Set
Method Description
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric
differences of two sets
symmetric_difference_update()
inserts the symmetric differences
from this set and another
union() Return a set containing the union of
sets
update() Update the set with the union of this set
and
others
Dictionary
A dictionary is a collection which is unordered, changeable and
indexed.In Python dictionaries are written with curly brackets,
and they have keys and values.
eg: thisdict
= {"brand": "Ford“,"model": "Mustang“,"year": ”1964”}

 You can access the items of a dictionary by referring to its key name,
inside square brackets.
eg: x = thisdict["model"] get the value of the "model" key:
 You can change the value of a specific item by referring to its key name.
eg:thisdict["year"] = 2018
 You can loop through a dictionary by using a for loop.
# print all key names in the dictionary, one by one
eg:for x in thisdict:
print(x)
# print all values in the dictionary ,one by one
eg:for x in thisdict:
print(thisdict[x])
Dictionary
# use the values() function to return values of a
dictionary
eg:for x in thisdict.values():
print(x)
# Loop through both keys and values, by using
the items() function
eg:for x, y in thisdict.items():
print(x, y)
 to determine if a specified key is present in a dictionary use
the in keyword
eg: if "model" in thisdict:
print("Yes, 'model' is one of the keys ")
 to determine how many items (key-value pairs) a dictionary
has, use the len() method.
eg:print(len(thisdict))
Dictionary
 Adding an item to the dictionary is done by using a new index key
and assigning a value to it
eg:thisdict["color"] = "red“
 There are several methods to remove items from a dictionary
# The pop() method removes the item with the specified key
name
eg:thisdict.pop("model")
# The popitem() method removes the last inserted item
eg:thisdict.popitem()
# The del keyword removes the item with the specified key
name
eg: del thisdict["model"]
# The del keyword can also delete the dictionary completely
eg: del thisdict
# The clear() keyword empties the dictionary:
eg: thisdict.clear()
Dictionary
 There are ways to make a copy,
#one way is to use the built-in Dictionary
method copy().
eg:mydict = thisdict.copy()
#Another way to make a copy is to use the built-
in method dict().
eg:mydict = dict(thisdict)
 A dictionary can also contain many dictionaries, this is called nested
dictionaries.
eg: myfamily = {"child1" : {"name" : "Emil“,"year" : 2004},
"child2" : {"name" : "Tobias“,"year" : 2007},
"child3" : {"name" : "Linus“,"year" : 2011}}
or, to nest three dictionaries that already exists as
child1 = {"name" : "Emil“,"year" : 2004}
child2 = {"name" : "Tobias“,"year" : 2007}
child3 = {"name" : "Linus“,"year" : 2011}
myfamily = {"child1" : child1, "child2" :
child2,"child3" : child3}
Dictionary
 It is also possible to use the dict() constructor to make a
new dictionary:
eg :thisdict = dict(brand="Ford", model="Mustang",
year=1964)
*note that keywords are not string literals
*note the use of equals rather than colon for
the assignment
Dictionary Methods
Method Description
 clear() Removes all the elements from the
dictionary
 copy() Returns a copy of the dictionary
 fromkeys() Returns a dictionary with the specified
keys and
values
 get() Returns the value of the specified key
 items() Returns a list containing the a tuple for
Dictionary
 keys() Returns a list containing the dictionary's
keys
 pop() Removes the element with the specified key
 popitem() Removes the last inserted key-value pair
 setdefault() Returns the value of the specified key. If the

key does not exist insert the key, with the


specified value
 update() Updates the dictionary with the specified
key-value pairs
 values() Returns a list of all the values in the
dictionary

You might also like