5 Python Collections
5 Python Collections
Collections
Introduction
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.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the
right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.
LIST
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
It can have any number of items and they may be of different types (integer, float, string
etc.).
How to create a list?
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
How to access elements from a list?
Index: a number specifying the position of an element in a listIndex of first element in the list is 0,
second element is 1, and n’th element is n-1
Negative indexes identify positions relative to the end of the list
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5
elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
Negative indexing
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Searches the list for a specified value and returns the position of where it was found
insert() S
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
Operators Description Example
+ Concatenation List1+List2
* Repetition List2*2
[] Slice List2[2]
In Membership
Slicing
Slice: a span of items that are taken from a sequence
List slicing format: list[start : end]
Span is a list containing copies of elements from start up to, but not including,
end
If start not specified, 0 is used for start index
If end not specified, len(list) is used for end index
Slicing expressions can include a step value and negative indexes relative to end
of list
We can access a range of items in a list by using the slicing operator (colon).
Examples:
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5]) # elements 3rd to 5th
print(my_list[:-5]) # elements beginning to 4th
print(my_list[5:]) # elements 6th to end
print(my_list[:])# elements beginning to end
Slicing can be best visualized by considering the index to be between the elements as
shown below. So if we want to access a range, we need two index that will slice that
portion from the list.
Loop Through a List
You can loop through the list items by using a for loop:
Print all items in the list, one by one:
mylist = ["apple", "banana", "cherry"]
for x in mylist:
print(x)
Check if Item Exists- in and not in
operator(Membership operator)
You can use the in operator to determine whether an item is contained in a list
General format: item in list
Returns True if the item is in the list, or False if it is not in the list
Similarly you can use the not in operator to determine whether an item is not in a
list
Check if "apple" is present in the list:
mylist = ["apple", "banana", "cherry"]
if "apple" in mylist:
print("Yes, 'apple' is in the fruits list")
List Length
To determine how many items a list has, use
the len() method:
Print the number of items in the list:
mylist = ["apple", "banana", "cherry"]
print(len(mylist))
Add Items to list
To add an item to the end of the list, use the append() method:
Using the append() method to append an item:
mylist = ["apple", "banana", "cherry"]
mylist.append("orange")
print(mylist)
To add an item at the specified index, use the insert() method:
Insert an item as the second position:
mylist = ["apple", "banana", "cherry"]
mylist.insert(1, "orange")
print(mylist)
Remove Item from list
There are several methods to remove items from a list:
The remove() method removes the specified item.
mylist = ["apple", "banana", "cherry"]
mylist.remove("banana")
print(mylist)
The pop() method removes the specified index, (or the last item if index is not
specified):
mylist = ["apple", "banana", "cherry"]
mylist.pop()
print(mylist)
del keyword
The del keyword removes the specified index
mylist = ["apple", "banana", "cherry"]
del mylist[0]
The del keyword can also delete the list completely
mylist = ["apple", "banana", "cherry"]
del mylist
#this will cause an error because "mylist" no longer exists.
The clear() method empties the list:
mylist = ["apple", "banana", "cherry"]
mylist.clear()
print(mylist)
Concatenating List
Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable
list.
sort() Parameters: By default, sort() doesn't require any extra parameters. However, it has two optional parameters:
reverse - If true, the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison
Return value from sort(): sort() method doesn't return any value. Rather, it changes the original list.
If you want the original list, use sorted().
vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
print('Sorted list:', vowels)
Sort() example:
OR Sort the list in descending order
vowels.sort(reverse=True)
print('Sorted list (in Descending):', vowels)
To make a copy of a list you must copy each element of the list
print(id(l1))
print(id(l2))
print(id(l3))
print(id(l4))
Cloning a List
You can use the slice operator with a default START and END to clone
an entire list (make a copy of it)
For example:
a = [ 5, 10, 50, 100]
b = a[: ]
Now, a and b point to different copies of the list with the same data
values.
Zipping List together
These aren't really functions, but they can replace functions (or maps, filters, etc)
A list comprehension can optionally contain more for or if statements. An
optional ifstatement can filter out items for the new list. Here are some examples.
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']
Some more examples:
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
Set
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {1, 2, 4, 5}
print(A.issubset(B))
print(B.issubset(A))
print(A.issubset(C))
print(C.issubset(B))
issuperset()
The issuperset() method returns True if a set has every elements of another set (passed as an
argument). If not, it returns False.
Set A is said to be the superset of set B if all elements of B are in A.
here, set A is a superset of set B and B is a subset of set A.
The syntax of issuperset() is:
A.issuperset(B)
Return Value from issuperset()
The issuperset() returns
• True if A is a superset of B
• False if A is not a superset of B
Example:
A = {1, 2, 3, 4, 5}
B = {1, 2, 3}
C = {1, 2, 3}
print(A.issuperset(B))
print(B.issuperset(A))
print(C.issuperset(B))
True
False
True
Frozen Set
These sets cannot be redefined once they are declared as
frozen set. Hence, they are called as immutable set.
Set2=frozenset({‘a’,’b’,’c’,’d’})
This datatype supports methods like copy(), difference(),
intersection(), isdisjoint(), issubset(), issuperset(),
symmetric_difference() and union(). Being immutable it does
not have method that add or remove elements.
STRING
String
A string is a sequence of characters. The string is a sequence of Unicode character in Python. Unicode was
introduced to include every character in all languages and bring uniformity in encoding.
Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be
used in Python but generally used to represent multiline strings and docstrings.
my_string = 'Hello'
my_string = "Hello"
my_string = '''Hello'''
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to the
world of Python"""
Accessing String
We can access individual characters using indexing and a range of characters using slicing. Trying to access a character out of index range will
raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError. Python allows negative
indexing for its sequences.
str = 'programing'
print('str = ', str)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
#slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
#slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
Update string:
The existing string can be update by (re)assigning a
variable to another string. The new value can be
related to its previous value or to a completely
different string altogether. For example −
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python' )
output: Updated String :- Hello Python
String functions
4 string functions.docx
Backslash notation Hexadecimal character Description
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
* Repetition - Creates new strings, concatenating multiple copies of the a*2 will give -HelloHello
same string
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
In Membership - Returns true if a character exists in the given string H in a will give 1
not in Membership - Returns true if a character does not exist in the given M not in a will give 1
string
r/R Raw String - Suppresses actual meaning of Escape characters. The print r'\n' prints \n and print R'\n'prints \n
syntax for raw strings is exactly the same as for normal strings with
the exception of the raw string operator, the letter "r," which precedes
the quotation marks. The "r" can be lowercase (r) or uppercase (R)
and must be placed immediately preceding the first quote mark.
%c Character
%o octal integer
else:
print(“e is not present in the string”)
Concatenation of Two or More Strings
string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits '0123456789'
string.hexdigits '0123456789abcdefABCDEF'
string.octdigits '01234567'
string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV
WXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
DICTIONARY
Dictionary
Create and print a dictionary:
Empty dictionary can be created as shown
dict1={}
Print(dict1)
Print(type(dict1))
Dictionary with elements
dict2={‘name’:’akshay’,’age’:21,’marks’:88}
print(dict2)
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(dict1)
Building Dictionary faster using zip()
print(key)
print (key,value)
print (value)
Adding Elements to dictionary
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
EXAMPLE:
dict2={‘name’:’akshay’,’age’:21,’marks’:88}
print(dict2)
dict2[‘city’]=‘London’
print(dict2)
EXAMPLE:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Remove or delete items:
Three ways-
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Remove or delete items:
The popitem() method removes the last inserted item (in versions before 3.7, a random
item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Remove or delete items:
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Remove or delete items:
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.
Remove or delete items:
The clear() keyword empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Change Values
Youcan change the value of a specific item by referring to its key
name:
Change the "year" to 2018:
dict1={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
dict1["year"] = 2018
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Print all key names in the dictionary, one by one:
for x in dict1:
print(x)
print(dict1[x])
You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary Length
To determine how many items (key-value pairs) a
dictionary has, use the len() method.
Print the number of items in the dictionary:
print(len(thisdict))
The dict() Constructor
Itis also possible to use the dict() constructor to make
a dictionary:
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
print(thisdict)
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 each key value pair
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
NESTED
DICTIONARY
What is Nested Dictionary in
Python?
InPython, a nested dictionary is a dictionary inside a
dictionary. It's a collection of dictionaries into one single
dictionary.
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
Here,the nested_dict is a nested dictionary with the dictionary
dictA and dictB. They are two dictionary each having own key
and value.
Create a Nested Dictionary
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
How to change or add elements in a nested
dictionary?
Example : people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people[3]) When we run above program, it will output: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}
In the above program, we create an empty dictionary 3 inside the dictionary people.
Then, we add the key:value pair i.e people[3]['Name'] = 'Luna' inside the dictionary 3. Similarly, we do this for key age, sex
and married one by one. When we print the people[3], we get key:value pairs of dictionary 3.
Add another dictionary to the nested
dictionary
Example 4:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}}
people[4] = {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}
print(people[4])
When we run above program, it will output: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married':
'Yes'}
In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age
and sex with respective values. Then we print the people[4], to see that the dictionary 4is added in
nested dictionary people.
Delete elements from a Nested
Dictionary
In Python, we use “ del “ statement to delete elements from nested dictionary.
Example 5: How to delete elements from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}
del people[3]['married']
del people[4]['married']
print(people[3])
print(people[4])
When we run above program, it will output: {'name': 'Luna', 'age': '24', 'sex': 'Female'}
{'name': 'Peter', 'age': '29', 'sex': 'Male'}
Delete Dictionary from nested dictionary
Using the for loops, we can iterate through each elements in a nested
dictionary.
Example 7: How to iterate through a Nested dictionary?
people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}
for p_id, p_info in people.items():
print("\nPerson ID:", p_id)
for key in p_info:
print(key + ':', p_info[key])
ARRAY IN PYTHON
Array : How to create
Arrays are mutable; their elements can be changed in a similar way like lists.
import array as arr
numbers=arr.array('i',[1,2,3,5,7,10])
# changing first element
numbers[0]=0
print(numbers)# Output: array('i', [0, 2, 3, 5, 7, 10])
# changing 3rd to 5th element
numbers[2:5]=arr.array('i',[4,6,8])
print(numbers)# Output: array('i', [0, 2, 4, 6, 8, 10])
Add items to array
We can add one item to a list using append() method or add several items
using extend()method.
import array as arr
numbers=arr.array('i',[1,2,3])
numbers.append(4)
print(numbers)# Output: array('i', [1, 2, 3, 4])
# extend() appends iterable to the end of the array
numbers.extend([5,6,7])
print(numbers)# Output: array('i', [1, 2, 3, 4, 5, 6, 7])
concatenate two arrays using + operator.
You can use the for in loop to loop through all the elements of
an array.
Example
Print each item in the cars array:
for x in cars:
print(x)
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 elem
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
Just like dictionaries, sets have no order in their collection of items. Not like lists.
Set requires the items contained in it to be hashable, lists store non-hashable items.
Sets require your items to be unique and immutable. Duplicates are not allowed in
sets, while lists allow for duplicates and are mutable.
You should make use of sets when you have an unordered set of unique, immutable
values that are hashable.
You aren’t sure which values are hashable?
Take a look below just to be sure:
Hashable Non-Hashable
Floats Dictionaries
Integers Sets
Tuples Lists
Strings
frozenset()
How To Convert Lists Into Other Data
Structures
You can change a list to a tuple in Python by using the tuple() function.
Pass your list to this function, and you will get a tuple back!
Remember: tuples are immutable. You can’t change them afterward!
Tip: you can try transforming your listOfStrings into a tuple in the
interactive exercise of the next section.
How To Convert Your List To A Set In
Python
As you will remember, a set is an unordered collection of unique items. That means not only means
that any duplicates that you might have had in your original list will be lost once you convert it to a
set, but also the order of the list elements.
You can change a list into a set with the set() function. Just pass your list to it!
Now practice converting your list listOfStrings into a tuple and a set here:
# Pass your list to `tuple()`
tuple(___)
# Transform your list into a set
set(___)
How To Convert Lists To A Dictionaries
A dictionary works with keys and values, so the conversion from a list to a dictionary might be less straightforward. Let’s say
you have a list like this:
helloWorld = ['hello','world','1','2']
You will need to make sure that ‘hello’ and ‘world’ and ‘1’ and ‘2’ are interpreted as key-value pairs. The way to do this is to
select them with the slice notation and pass them to zip().
zip() actually works like expected: it zips elements together. In this case, when you zip the helloWorld
elements helloWorld[0::2] and helloWorld[1::2], your output will be:
list(zip(helloWorld))
Note that you need to use list() to print out the result of the zip()function.
You will pass this to the dict() function, which will interpret hello as a key and world as a value. Similarly, 1 will be interpreted
as a key and 2 as a value.
Run the code below to confirm this:
# Convert to a dictionary
helloWorldDictionary = dict(zip(helloWorld[0::2], helloWorld[1::2]))
# Print out the result
print(helloWorldDictionary)
Note that the second element that is passed to the zip() function makes use of the step value to make sure that only
the world and 2 elements are selected. Likewise, the first element uses the step value to select hello and 1.
If your list is large, you will probably want to do something like this:
a = [1, 2, 3, 4, 5]
# Create a list iterator object
i = iter(a)
# Zip and create a dictionary
print(dict(zip(i, i)))
Note that an iterable object can give you an iterator. The iterator, which has a .__next__ method, holds information on where exactly
you are in your iteration: it knows what the next element in the iteration is.
How To Convert A Tuple To A List
count1=0
count2=0
for i in string1:
count1=count1+1
for j in string2:
count2=count2+1
if(count1<count2):
print(string2)
elif(count1==count2):
else:
print(string1)
Python Program to Count Number of
Lowercase Characters in a String
string=input("Enter string:")
count=0
for i in string:
if(i.islower()):
count=count+1
print("The number of lowercase characters is:")
print(count)
DICTIONARY
Python Program to Add a Key-Value
Pair to the Dictionary
key=int(input("Enter the key (int) to be added:"))
value=int(input("Enter the value for the key to be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d)
Python Program to Concatenate Two
Dictionaries Into One
d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")
print(d1)
Python Program to Check if a Given
Key Exists in a Dictionary or Not
d={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
else:
print("Key isn't present!")
PythonProgram to Generate a Dictionary that
Contains Numbers (between 1 and n) in the
Form (x,x*x).
n=int(input("Enter a number:"))
d={x:x*x for x in range(1,n+1)}
print(d)
Python Program to Sum All the Items in a
Dictionary
d={'A':100,'B':540,'C':239}
print("Total sum of values in the
dictionary:")
print(sum(d.values()))
Python Program to Multiply All the Items
in a Dictionary
d={'A':10,'B':10,'C':239}
tot=1
for iin d:
tot=tot*d[i]
print(tot)
Python Program to Remove the Given
Key from a Dictionary
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Python Program to Form a Dictionary
from an Object of a Class
class A(object):
def __init__(self):
self.A=1
self.B=2
obj=A()
print(obj.__dict__)
Python Program to Map Two Lists
into a Dictionary
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
set
Python Program to Count the
Number of Vowels Present in a String
using Sets
s=input("Enter string:")
count = 0
vowels = set("aeiou")
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)
Python Program to Check Common
Letters in Two Input Strings
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)&set(s2))
print("The common letters are:")
for i in a:
print(i)
Python Program that Displays
which Letters are in the First
String but not in the Second
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)-set(s2))
print("The letters are:")
for i in a:
print(i)
Python Program that Displays which
Letters are Present in Both the
Strings
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)|set(s2))
print("The letters are:")
for i in a:
print(i)
Python Program that Displays
which Letters are in the Two
Strings but not in Both
s1=input("Enter first string:")
s2=input("Enter second string:")
a=list(set(s1)^set(s2))
print("The letters are:")
for i in a:
print(i)
ASSIGNMENTS
Assignments
1. Write a program that prints all the numbers from 1 to 100. Your program should have
much fewer than 100 lines of code!
2. Suppose you have a Python program that read in a whole page from a book into an
array PAGE, with each item of the array corresponding to a line. Add code to this
program to create a new array SENTENCES that contains the same text, but now with
each element in SENTENCES being one sentence.
3. Let d be a dictionary whose pairs key:value are country:capital. Write a Python
program that prints the keys and values of d, with the keys sorted in alphabetical order.
Test your program on
d = {“France”:”Paris”,”Belgium”:”Brussels”,”Mexico”:”Mexico
City”,”Argentina”:”Buenos Aires”,”China”:”Beijing”}
4. Write a Python program which accepts the user's first and last name and print them in
reverse order with a space between them.
5. Write a Python program to display the first and last colors from the following list.
color_list = ["Red","Green","White" ,"Black"]
6. Write a Python program to count the number 4 in a given list.
7. Write a Python program to test whether a passed letter is a vowel or not.
8. Write a Python program to check whether a specified value is contained in a group of
values.
9. Write a Python program to concatenate all elements in a list into a string and return it.
10. Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2.
Test Data :
color_list_1 = set(["White", "Black", "Red"]) color_list_2 = set(["Red", "Green"])
Expected Output : {'Black', 'White'}
11. Write a Python program to count the number occurrence of a specific character in a string.
12. Write a Python program to remove the first item from a specified list.
13. Write a Python program to sum of all counts in a collections?
14. Write a Python program to print the length of the series and the series from the given 3rd term, 3rd last term and the sum of a
series.
15. Write a Python program to replace a string "Python" with "Java" and "Java" with "Python" in a given string.
Input:
English letters (including single byte alphanumeric characters, blanks, symbols) are given on one line. The length of the input
character string is 1000 or less.
Input a text with two words 'Python' and 'Java'
Python is popular than Java
Java is popular than Python