unit-3 py
unit-3 py
The list is a sequence data type which is used to store the collection of data.
L = [20, ‘aabb’,35.43,[‘e’,’b’,’m’]]
Lists are the simplest containers that are an integral part of the Python language. Lists need
not be homogeneous always which makes it the most powerful tool in Python. A single list
may contain different data types like Integers, Strings, as well as Objects. Lists are mutable,
and hence, they can be altered even after their creation.
Output
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
apple
banana
A list may contain duplicate values with their distinct positions and hence, multiple distinct
or duplicate values can be passed as a sequence at the time of list creation.
# Creating a List with
# the use of Numbers
# (Having duplicate values)
List=[1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)
Length of a List
In order to find the number of items present in a list, we can use the len() function.
my_list=[1,2,3]
print(len(my_list))
# output 3
Negative indexing
In Python, negative sequence indexes represent positions from the end of the array. Instead
of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
List=[1, 2, 'python', 4, 'For', 6, 'python']
# Creating a List
List=[]
print("Initial blank List: ")
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
# Creating a List
List=[1,2,3,4]
print("Initial List: ")
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
Output
Initial List:
[1, 2, 3, 4]
# Creating a List
List=[1, 2, 3, 4]
print("Initial List: ")
print(List)
Reversing a List
A list can be reversed by using the reverse() method in Python.
# Reversing a list
mylist =[1, 2, 3, 4, 5, 'Geek', 'Python']
mylist.reverse()
print(mylist)
Output
['Python', 'Geek', 5, 4, 3, 2, 1]
# Creating a List
List=[1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)
# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
Output
List after popping an element:
[1, 2, 3, 4]
Slicing of a List
We can get substrings and sublists using a slice. In Python List, there are multiple ways to
print the whole list with all the elements, but to print a specific range of elements from the
list, we use the Slice operation.
Slice operation is performed on Lists with the use of a colon(:).
To print elements from beginning to a range use:
[: Index]
To print elements from end-use:
[:-Index]
To print elements from a specific Index till the end use
[Index:]
To print the whole list in reverse order, use
[::-1]
Note – To print elements of List from rear-end, use Negative Indexes.
# Creating a List
List=['G', 'E', 'E', 'K', 'S', 'F',
'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)
print(odd_square)
Output
[1, 9, 25, 49, 81]
List Methods
Function Description
Append() Add an element to the end of the list
Extend() Add all elements of a list to another list
Insert() Insert an item at the defined index
Remove() Removes an item from the list
Clear() Removes all items from the list
Index() Returns the index of the first matched item
Count() Returns the count of the number of items passed as an argument
Sort() Sort items in a list in ascending order
Reverse() Reverse the order of items in the list
copy() Returns a copy of the list
Example
my_list = [5, 8, 'Tom', 7.50, 'Emma']
# Withoutend_value
# Stating from 3nd item to last item
print(my_list[3:])
# Output [7.5, 'Emma']
Python Dictionary
An effective data structure for storing data in Python is dictionaries, in which can simulate
the real-life data arrangement where some specific value exists for some particular key.
Python Dictionary is used to store the data in a key-value pair format.
It is the mutable data-structure.
The elements Keys and values is employed to create the dictionary.
Keys must consist of just one element.
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be of any Python object. In contrast, the keys are the immutable Python object,
i.e., Numbers, string, or tuple. Dictionary entries are ordered as of Python version 3.7. In
Python 3.6 and before, dictionaries are generally unordered.
Creating the Dictionary
The simplest approach to create a Python dictionary is by using curly brackets {}, but there
are other methods as well. The dictionary can be created by using multiple key-value pairs
enclosed with the curly brackets {}, and each key is separated from its value by the colon
(:). The syntax to define the dictionary is given below.
Dict = {"Name": "Chris", "Age": 20}
In the above dictionary Dict, The keys Name and Age are the strings which comes under
the category of an immutable object.
Let's see an example to create a dictionary and print its content.
Code
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Python provides the built-in function dict() method which is also used to create the
dictionary.
The empty curly braces {} is used to create empty dictionary.
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Microsoft', 2: 'Google', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Praneeth'), (2, 'Varma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output
Empty Dictionary:
{}
Python Tuples
A Python Tuple is a group of items that are separated by commas. The indexing,
nested objects, and repetitions of a tuple are somewhat like those of a list, however
unlike a list, a tuple is immutable.
The distinction between the two is that while we can edit the contents of a list, we
cannot alter the elements of a tuple once they have been assigned.
Example
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (),
each one separated by a comma. Although it is not necessary to include
parentheses, doing so is advised.
A tuple can contain any number of items, including ones with different data types
(dictionary, string, float, list, etc.).
Code:
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Code
Output:
Code
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Indexing
To access an object of a tuple, we can use the index operator [], where indexing in
the tuple starts from 0.
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be
raised if we try to access an index from the tuple that is outside the range of the
tuple index. In this case, an index above 4 will be out of range.
We cannot give an index of a floating data type or other kinds because the index in
Python must be an integer. TypeError will appear as a result if we give a floating
index.
The example below illustrates how indexing is performed in nested tuples to access
elements.
Code
Output:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
Negative Indexing
The last item of the collection is represented by -1, the second last item by -2, and
so on.
Code
Output:
Slicing
In Python, tuple slicing is a common practise and the most popular method for
programmers to handle practical issues. Think about a Python tuple. To access a
variety of elements in a tuple, you must slice it. One approach is to use the colon
as a straightforward slicing operator (:).
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Code
Output:
Deleting a Tuple
Code
Output:
Code
Output:
Python Tuples is a collection of immutable objects that is more like to a list. Python
offers a few ways to work with tuples. These two approaches will be thoroughly
covered in this essay with the aid of some examples.
Count () Method
The number of times the specified element occurs in the tuple is returned by the
count () function of Tuple.
Code
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = T1.count(2)
print('Count of 2 in T1 is:', res)
# counting the appearance of java
res = T2.count('java')
print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The first instance of the requested element from the tuple is returned by the Index()
function.
Parameters:
begin (Optional): the index used as the starting point for searching
final (optional): The last index up until which the search is conducted
Index() Method
Code
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Tuple Membership Test
Using the in keyword, we can determine whether an item is present in the given
tuple or not.
Code
Output:
True
False
False
True
Iterating Through a Tuple
Code
Output:
Python
Tuple
Ordered
Immutable
Changing a Tuple
Code
Output:
To merge multiple tuples, we can use the + operator. Concatenation is the term for
this.
Using the * operator, we may also repeat a tuple's elements for a specified number
of times. This is already shown above.
Code
Output:
If a tuple includes immutable values like strings, numbers, or another tuple, it can
be used as a dictionary key. Since "lists" are mutable, they cannot be utilized as
dictionary keys.