Saturday, August 28, 2021

Python -Sets

 Python

Python - Sets 


Python Sets:

A set is created by placing all the items (elements) inside curly braces {}, separated by a comma, or by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float, tuple, string, etc.). But a set cannot have mutable elements like lists, sets, or dictionaries as its elements.

  • Sets are an unordered collection of unique elements. We can construct them by using the set() function.
  • Sets cannot contain duplicates.
  • Sets are mutable like lists.
  • You can create a non-empty set with curly braces by specifying elements separated by a comma.
  • Set items can be of any data type.
  • Sets can be any data type.
Example:
set1 = ("apple""banana""cherry")
set2 = {1579.03.9,'abc','cde'}
set3 = (1,2,3,4,5)
Empty_set = set()


Python Sets Functions and methods:

add()

  • add( ) - the method adds an element to the set.
  • This method takes the element to be added as an argument to the given set.


Example:

set_1  =  set()
set_1.add('hi!')
print(set_1)

Result:
{'hi!'}



update()


  • update( ) - the method helps to add multiple elements to a set.

Example:

set_2 = {5,7,9,3}
set_2.update([2, 3, 4])
print(set_2)

Result:
{2, 3, 4, 5, 7, 9}


remove()


  • Use remove( ) to remove an item/element from the set.
  • By default remove( ), removes the specified element from the set.
  • remove( ), takes the element as an argument.

Example:

set_3 = {1,6,34,12,32,46,'a','g','h'}
set_3.remove(46)
print(set_3)

Results:
{1, 12, 32, 34, 6, 'a', 'g', 'h'}

dict()


  • We can also create dictionary objects from a sequence of items that pair. This can be done using the  - dict( ) method.
  • dict( ), the function takes the list of paired elements as an argument in the list of tuples.


Example:

state_city = [ ( 'Andhrapradesh',' Visakhapatnam'),('Karnataka','Bangaluru'),('Telangana','Hyderabad')]

state_city = dict(state_city)

print(state_city)

Result:

{'Andhrapradesh': ' Visakhapatnam', 'Karnataka': 'Bangaluru', 'Telangana': 'Hyderabad'}


pop()


  • pop( )- the method removes and returns an element from a dictionary having the given key.

  • This method takes two arguments/parameters (i) key - key which is to be searched for removal, (ii) default - value which is to be returned when the key is not in the dictionary.




Example:

state_city = {'Andhrapradesh': ' Visakhapatnam', 'Karnataka': 'Bangaluru', 'Telangana': 'Hyderabad'}
state_city.pop("Telangana")
print(state_city)

Result:

{'Andhrapradesh': ' Visakhapatnam', 'Karnataka': 'Bangaluru'}



This is all about Python Sets, If any doubts comment down.

You can also read below...



 













Thursday, August 26, 2021

Python - Tuples

Tuples

Python - Tuples

Tuples:

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed, unlike lists and tuples that use parentheses, whereas lists use square brackets.
  • In Python tuples are very similar to lists, however, unlike lists, Tuples are immutable. It means they can not be changed.

  • We would use tuples to present things that should not be changed, such as days of the week, or dates on a calendar, etc.
  • Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples.

  • Updating or Deleting will not be possible with tuples, because tuples are immutable.

  • Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also.

  • The construction of a tuple using () with elements separated by commas.

Example:
tuple_1 = ('India', 'Andhrapradesh', 1993,21)
tuple_2 = (1, 2, 3, 4, 5 )
tuple_3 = "a", "b", "c", "d"

                The empty tuple is written as two parentheses containing nothing.
Empty_Tuple = ()


Tuple Indexing:


  • Tuples Indexing work just like in lists.
  • A tuple index refers to the location of an element in a tuple.
  • Remember the indexing begins from 0 in Python.
  • The first element is assigned an index of 0, the second element is assigned an index of 1.

Tuple Slicing:


  • We can use a : to perform slicing which gives everything up to a designated point.
  • The starting index is specified on the left of the ":"and the ending index is specified on the right of the ":".
  • Remember the element located at the right index is not included.


Tuple indexing and Slicing can be understood easily by the below example.

Python-Tuples


Basic Tuples Operations:

Tuples respond to the + and * operators much like strings. It means concatenation and repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all of the general sequence operations we used on strings in the lists.


Python ExpressionResultsDescription
len((1, 2, 3))3Length
(a, b, c) + (4, 5, 6)(a, b, c, 4, 5, 6)Concatenation
('abc',) * 4('abc', 'abc', 'abc', 'abc')Repetition
3 in (1, 2, 3)TrueMembership
for x in (1, 2, 3)
 print(x)
1 2 3Iteration

    

Built-in Tuple Functions:


Sr.No.Description to the Function
1cmp(tuple_1, tuple_2)

It compares elements of both the tuples.

2len(tuple)

It gives the total length of the tuple.

3max(tuple)

It returns item from the tuple with max value.

4min(tuple)

It returns item from the tuple with min value.

5tuple(seq)

It converts a list into tuple.



Why and when do we use Tuples?

  • You may be wondering, "Why to bother using tuples when they have fewer available methods?" To be honest, tuples are not used as often as lists in programming but are used when immutability is necessary. If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.
  • You will find them often in functions when you are returning some values.
  • You should now be able to create and use tuples in your programming as well as have an understanding of their immutability.




This is all about Tuples in Python...



You can also read the below links...

Monday, August 23, 2021

Python - Lists

 Python Lists



Earlier when discussing strings we introduced the concept of a sequence in Python

  • Lists can be thought of as the most general version of a sequence in Python.
  • Unlike strings, they are mutable, meaning the elements inside a list can be changed!
  • Lists are constructed with brackets "[ ]" and commas separating every element in the list.


The list is the most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. An important thing about a list is that items in a list need not be of the same type.

Example: 

list1 = ['Maths', 'manoj', 1993, 2021];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]


List Indexing:

  • Indexing work just like in strings.
  • A list index refers to the location of an element in a list.
  • Remember the indexing begins from 0 in Python.
  • The first element is assigned an index 0, the second element is assigned an index of 1, and so on and so forth.

L = ['State', 'India', 'Hello!']
Python ExpressionResultsDescription
L[2]Hello!Offsets start at zero
L[-2]IndiaNegative: count from the right
L[1:]['India', 'Hello!']Slicing fetches sections


List Slicing:

  • We can use a : to perform slicing which grabs everything up to a designated point.
  • The starting index is specified on the left of the : and the ending index is specified on the right of the :.
  • Remember the element located at the right index is not included.



Python


List Operations:


Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.

In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.


Python ExpressionResultsDescription
len([1, 2, 3,4,5])5Length
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
['12'] * 4['12', '12', '12', '12']Repetition
2 in [1, 2, 3]TrueMembership
for x in [1, 2, 3,4]
 print(x)
1 2 3 4

Iteration


List Functions:

len()

  • len() the function returns the length of the list.

min()

  • min() the function returns the minimum element of the list
  • min() function only works with lists of similar data types

max()

  • max() the function returns the maximum element of the list
  • max() function only works with lists of similar data types

sum()

  • sum() the function returns the sum of the elements of the list
  • sum() function only works with lists of numeric data types

sorted()

  • sorted() the function returns the sorted list
  • sorted() the function takes reverse boolean as an argument
  • sorted() function only works on a list with similar data types

Python ExpressionResultsDescription
len([1, 2, 3,4,5])5Length
min([1, 2, 3,4,5])small number in list
max(['Argue','Burglar','Parent','Linear','shape'])'shape'maximum element in list
sum([6,9,1,3,5.5])24.5sum of all elements in the list
sorted([6,9,1,3,5.5])[1, 3, 5.5, 6, 9]

sorted list

List Methods:

  • If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python, however, tend to be more flexible than arrays in other languages for two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).
  • Let's go ahead and explore some more special methods for lists:

append()

  • Use the append() method to permanently add an item to the end of a list.
  • append() the method takes the element which you want to add to the list as an argument

Example:
list = [1, 2, 3, 1, 1, 1, 3, 10, 5, 8]
list = list.append('Append!')
print(list)

Results:
[1, 2, 3, 1, 1, 1, 3, 10, 5, 8, 'Append!']


extend()

  • Use the extend() method to merge a list to an existing list.
  • extend() the method takes a list or any iterable(don't worry about it now) as an argument.
  • Quite helpful when you have two or more lists and you want to merge them together.
Example:

list = [1, 2, 3, 1, 1, 1, 3, 10, 5, 8]

list = list.extend(['cuba','france','India'])
print(list)

Results:
[1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'cuba','france','India']


pop()

  • Use pop() to "pop-off" an item from the list.
  • By default pop() takes off the element at the last index, but you can also specify which index to pop off.
  • pop() takes the index as an argument and returns the element which was popped off.


Example:
list =  [1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'cuba','france','India']
list = list.pop() # 0th index
print(list)

Results:
'India'


remove()

  • Use remove() to remove an item/element from the list.
  • By default "remove()"removes the specified element from the list.
  • remove() takes the element as an argument.


Example:
list =  [1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'cuba','france','India']
list = list.remove('cuba')
print(list)

Results:
[1, 2, 3, 1, 1, 1, 3, 10, 5, 8,'france','India']


count()

  • The count() the method returns the total occurrence of a specified element in the list.


Example:
list = [2, 3, 1, 1, 1, 3, 10, 5, 8, 'Append', 'cuba','france','India','cuba']
list = list.count('cuba') # Count the number of times element  occurs in the list
print(list)

Results:
2


index()

  • The index() the method returns the index of a specified element in the list.


Example:

list = [2, 3, 1, 1, 1, 3, 10, 5, 8, 'Append!', 'cuba','france','India']
list = list.index('cuba')
print(list)

Results:
10


sort()

  • Use sort() to sort the list in either ascending/descending order.
  • The sorting is done in ascending order by default.
  • sort() the method takes the reverse boolean as an argument.
  • sort() the method only works on a list with elements of the same data type.


Example:

list = [6, 9, 1, 3, 5]
list.sort()
print(list)

Results:
[1, 3, 5, 6, 9]



reverse()

  • reverse() method reverses the list elements.


Example:
list = [1, 1, 1, 1, 1.43, 2, 3, 3, 5, 8, 10, 'cuba', 'france']
list.reverse()
print(list)

Results:

['france', 'cuba', 10, 8, 5, 3, 3, 2, 1.43, 1, 1, 1, 1]



Nested Lists:

  • A great feature of Python data structures is that they support nesting. This means we can have data structures within data structures. For example A list inside a list.

Example:
list_1 = [1,2,3]
list_2 = ['b','a','d']
list_3 = [7,8,9]

list_of_lists  =  [list_1,list_2,list_3] # Make a list of lists to form a matrix
print(list_of_lists)

Results:
[[1, 2, 3], ['b', 'a', 'd'], [7, 8, 9]]

This is all about List in Python...



You can also read the below links...





Python - Conditional statements ,if condition in python

 Python - if - Conditional statements What is the if condition in python? Decision-making is the anticipation of conditions occurring while ...