what are data types in python? Different Data Types In Python with Examples
what are data types in python? Different Data Types In Python with Examples
In Python, a data type is a category of values. Python has
several built-in data types, including integers (int), floating-point numbers
(float), and strings (str). Here's a brief overview of each of these data
types, along with examples of how to create and use them:
- Integers
(int) are whole numbers, such as 42 or -17. You can create an integer in
Python by typing a whole number directly, like this:
x = 42 y = -17
Creating an integer in Python is quite simple. You can
create an integer by typing a whole number directly, like this:
x = 42
y = -17
You can perform basic mathematical operations on integers,
such as addition, subtraction, multiplication, division, and modulo. Here are
some examples:
a = 7
b = 3
# addition
c = a + b
print(c) # prints 10
# subtraction
c = a - b
print(c) # prints 4
# multiplication
c = a * b
print(c) # prints 21
# division
c = a / b
print(c) # prints 2.3333333333333335
# modulos
c = a % b
print(c) # prints 1
- Floating-point
numbers (float) are numbers with decimal points, such as 3.14 or -2.5.
You can create a float in Python by typing a decimal number directly, like
this:
x = 3.14 y = -2.5
- Strings
(str) are sequences of characters, such as "hello" or
"goodbye". You can create a string in Python by enclosing a
sequence of characters in quotes, like this:
x = "hello" y = 'goodbye'
A string in Python is a sequence of characters. Strings are
used to store and manipulate text and are one of the most widely used data
types in Python.
Creating a string in Python is easy. You can create an empty
string by enclosing an empty pair of quotes, like this:
my_string = ""
You can also create a string with some initial text by
enclosing the text in a pair of single or double quotes, like this:
my_string = "Hello, World!"
You can access the individual characters in a string by
referring to their index, which is an integer value that represents the
position of a character in the string. You can access a character of a string by
using the square brackets [] and the index of the character you want to access,
like this:
x = my_string[1] print(x) # prints "e"
You can also use negative indexing to access characters from
the end of the string
x = my_string[-1] print(x) # prints "!"
Python strings are immutable, meaning that you can't change
the characters of a string once it is created. However, you can create a new
string with the modified characters using string concatenation and replication.
new_string = my_string + " Have a good day."
You can use the built-in len() function to find the
length of the string, and the built-in min() and max() functions
to find the smallest and largest character in a string, respectively.
print(len(my_string)) # prints 13
print(min(my_string)) # prints ' '
print(max(my_string)) # prints 'r'
Python also provide many useful string methods like lower(),
upper(), find(), replace(), split(), join()
etc.
- lower():
Convert the string to lower case
- upper():
Convert the string to upper case
- find()
: Returns the index of the first occurrence of the specified value
- replace():
Replaces a specified phrase with another specified phrase
- split()
: Splits the string into substrings
- join()
: Joins the elements of an iterable to the end of the string.
print(my_string.lower()) # prints "hello, world!"
print(my_string.upper()) # prints "HELLO, WORLD!"
print(my_string.find("World")) # prints 7
new_string = my_string.replace("World", "Python")
In this way, python strings are widely used in many
applications, from simple text processing to more complex natural language
processing tasks, and provide rich set of inbuilt functions and methods for
manipulation and formatting of text.
- List
- It is a collection which is ordered and changeable. Allows duplicate
members. You can create a list in python using square brackets []
A list in Python is an ordered collection of items, which
can be of any type, such as integers, strings, or other objects. Lists are
defined by enclosing a comma-separated list of items in square brackets [].
Creating a list in Python is quite simple. You can create an
empty list using square brackets with no items inside, like this:
my_list = []
You can also create a list with some initial items by
listing them inside the square brackets and separating them with commas, like
this:
my_list = [1, 2, "hello", 4.5]
Since lists are ordered collections, you can access the
items of a list by referring to their index, which is an integer value that
represents the position of an item in the list. You can access an item of a
list by using the square brackets [] and the index of the item you want to
access, like this:
x = my_list[1]
print(x) # prints 2
You can also use negative indexing to access items from the
end of the list
x = my_list[-1]
print(x) # prints 4.5
One of the most important and widely used feature of list is
that, lists are mutable, meaning you can change the elements of a list after it
is created. You can use the square brackets and the assignment operator (=) to
change the value of an item in a list, like this:
my_list[1] = 3
You can use the built-in len() function to find the length
of the list, and the built-in min() and max() functions to find the smallest
and largest element in a list, respectively.
print(len(my_list)) # prints 4
print(min(my_list)) # prints 1
print(max(my_list)) # prints 'hello'
Lists also provide various useful built-in functions, such
as append(), insert(), extend(), remove(), pop(), index() and clear(). You can
use the append() function to add a single item to the end of the list, like
this:
my_list.append(6)
You can use the extend() function to add multiple items to
the list, using an iterable object like a list or a tuple.
my_list.extend([7,8,9])
In this way, python lists are widely used to store
collection of items, where order of the items is important. Lists are very
useful for many types of applications, as they are easy to use and provide a
wide range of built-in functions that can be used for many different tasks,
such as sorting, inserting, and removing items.
x = ["apple", "banana", "cherry"]
- Tuple
- It is similar to a list but it is ordered and unchangeable. Allows
duplicate members. You can create a tuple in python using parentheses ()
A tuple in Python is an ordered collection of items. Tuples
are similar to lists, but unlike lists, they are immutable, meaning that their
elements cannot be modified once created. Tuples are defined by enclosing a
comma-separated list of items in parentheses ().
Creating a tuple in Python is quite simple. You can create
an empty tuple using parentheses with no items inside, like this:
my_tuple = ()
You can also create a tuple with some initial items by
listing them inside the parentheses and separating them with commas, like this:
my_tuple = (1, 2, 3, 4)
Since tuples are ordered collections, you can access the
items of a tuple by referring to their index, just like you would with a list.
You can access an item of a tuple by using the square brackets [] and the index
of the item you want to access, like this:
x = my_tuple[1]
print(x) # prints 2
You can also use negative indexing to access items from the
end of the tuple
x = my_tuple[-1]
print(x) # prints 4
One of the main benefit of using tuples over lists is the
ability to use them as keys in a dictionary, because they are immutable.
You can use the built-in len() function to find the length
of the tuple, and the built-in min() and max() functions to find the smallest
and largest element in a tuple, respectively.
print(len(my_tuple)) # prints 4
print(min(my_tuple)) # prints 1
print(max(my_tuple)) # prints 4
A tuple can also be converted to a list using the list()
function and convert back to tuple using tuple() function.
tuple_to_list = list(my_tuple)
list_to_tuple = tuple(tuple_to_list)
In this way, python tuples are useful in many scenarios,
such as when you want to ensure that the elements of a collection won't change,
or when you need to use the collection as a key in a dictionary. Additionally,
Because they are immutable, they also use less memory as they can be stored in
a hash table, as keys.
x = ("apple", "banana", "cherry")
- Set
- It is collection which is unordered and unindexed. No duplicate members.
You can create a set in python using curly braces {} or set()
function
A set in Python is an unordered collection of unique items.
Sets are defined by enclosing a comma-separated list of items in curly braces
{} or by using the built-in set() function.
Creating a set in Python is quite simple. You can create an
empty set using curly braces with no items inside, like this:
my_set = set()
You can also create a set with some initial items by listing
them inside the curly braces or by passing an iterable object to the set()
function, like this:
my_set = {1,2,3,4,5}
my_set = set([1,2,3,4,5])
Sets are unordered collections, so the items have no
indexes. However, you can still check if an item is in a set by using the in
keyword, like this:
print(3 in my_set) # prints True
Sets also provide various useful built-in functions, such as
add(), update(), remove(), pop() and clear(). You can use the add() function to
add a single item to the set, like this:
my_set.add(6)
You can use the update() function to add multiple items to
the set. This function can take any iterable object, such as a list or a tuple,
as an argument, like this:
my_set.update([7,8,9])
You can remove an item from the set using the remove()
function. This function will raise an error if the item you're trying to remove
is not found in the set. So, discard() function is also there that doesn't
raise an error.
my_set.remove(3)
my_set.discard(10)
You can also use the pop() function to remove and return an
arbitrary item from the set. Since sets are unordered, there is no way to
predict which item will be removed.
x = my_set.pop()
In addition to these, there are some other functions like
difference() and intersection() which helps to find the difference and common
elements between multiple sets.
In this way, python sets are useful in many applications
where we need to keep a collection of unique items and perform set based
operations like union, intersection, difference and symmetric difference.
x = {"apple", "banana", "cherry"}
- Dictionary
- It is a collection which is unordered, changeable and indexed. No
duplicate members. You can create a dictionary in python using curly
braces { key : value }
x = {"name" : "John", "age" : 36}
A dictionary in Python is a collection of key-value pairs.
Dictionaries are unordered, changeable, and do not allow duplicate members.
They are defined by enclosing a comma-separated list of key-value pairs in
curly braces {}.
Creating a dictionary in Python is easy. You can create an
empty dictionary using curly braces with no items inside, like this:
my_dict = {}
You can also create a dictionary with some initial key-value
pairs by listing them inside the curly braces, like this:
my_dict = {'name': 'John', 'age': 36, 'city': 'New York'}
One of the most important and widely used feature of
dictionary is that, you can access the items of a dictionary by referring to
its key name. To access the value of a particular key, you can use the square
brackets [], like this:
x = my_dict["name"]
print(x) # prints "John"
Another way to access the items of a dictionary is through
the get() method. This method returns the value of the item with the
specified key. If the key is not found in the dictionary, it returns a default
value, which is None by default, but can be specified as a second argument to
the get() method.
x = my_dict.get("age")
print(x) # prints 36
You can also change the value of a particular key in the
dictionary by assigning a new value to that key, like this:
my_dict["age"] = 40
Dictionary also provide many inbuilt functions to make your
task easy, you can use keys() function to return a list of all the keys
in the dictionary, use values() to return a list of all the values in
the dictionary and items() to return a list of all the key-value pairs
in the dictionary.
print(my_dict.keys()) # prints
["name","age","city"]
print(my_dict.values()) # prints
["John",40,"New York"]
print(my_dict.items()) # prints [("name","John"),("age",40),("city","New York")]
You can also use len() function to find the length of
the dictionary, and del statement to remove a key-value pair from the
dictionary.
print(len(my_dict)) # prints 3 del my_dict["city"]
In this way, the python dictionaries are widely used in many
application, as they are very useful to store and retrieve data based on keys,
rather than indexing. They also provide various methods and functions that
makes data manipulation and access very easy.
These are some basic data types that python supports.
However, Python has many more built-in types and also supports user-defined
types through class and objects.
Comments
Post a Comment