Data Types & Structures, Slicing, and Indexing in Python

Understanding Data Types & Structures, Slicing, and Indexing in Python



What is Python?

Python is known for its readability, simplicity, and ease of learning. It has a vast and active community of developers who contribute to its libraries and frameworks, making it a highly versatile language. Python is used for various applications such as web development, scientific computing, data analysis, artificial intelligence, and machine learning.

Python's syntax is designed to be more natural and readable than other programming languages, making it easier to understand and maintain code. Its extensive standard library supports many common programming tasks and allows for the creation of scalable and complex applications.

Python has a unique feature called the "Pythonic" way of coding, which emphasizes code readability and elegance. This approach encourages programmers to write simple, readable, and maintainable code.

Python is an interpreted language, which means it does not require compiling before running the code. Therefore, it is a fast and efficient language for rapid development and prototyping.

In summary, Python is a versatile, high-level programming language that is easy to learn and understand. It is widely used in various applications, and its readability and elegance make it a popular and sought-after choice by developers around the world.


Introduction to Python Data Types




Data Types are used to define the type of a variable. It defines what type of data we are going to store in a variable. The data stored in memory can be of many types. Variables can hold values, and every value has a data type. Python is a dynamically typed language; hence we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type. Python enables us to check the type of the variable used in the program. Python provides us with the type() function, which returns the type of the variable passed.


Data types in Python.

  1. Numbers (Integer)
  2. String
  3. List
  4. Tuple
  5. Dictionary
  6. Sets
  7. Boolean


1. Numbers (Integer):-

Number stores numeric values. Number objects are created when you assign a value to them. The integer, float, and complex values belong to a Python Numbers data type.

Python supports four different numerical types −

i. Integers:-  (signed integers) 

This value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals). In Python, there is no limit to how long an integer value can be.

ii. Long Integers:-  (long integers, they can also be represented in octal and hexadecimal)

Integer type with unlimited length. In Python 2.2 and later, Ints are automatically turned into long ints when they overflow. Dropped since Python 3.0, use int type instead.

iii. Float:-  (floating point real values)

This value is represented by the float class. It is a real number with a floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a  positive or negative integer may be appended to specify scientific notation

iv. Complex:-  (complex numbers)

A complex number is represented by a complex class. It is specified as (real part)+(imaginary part)j

For example – 2+3j


Important Note:-

  • Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.

  • A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.

 For Example:-

# integer variable.

a=100

print("The type of variable having value", a, " is ", type(a))


# Long Integer variable

b=187687654564658970978909869576453

print("The type of variable having value", b, " is ", type(b))


# float variable.

c=20.345

print("The type of variable having value", c, " is ", type(c))


# complex variable.

d=10+3j

print("The type of variable having value", d, " is ", type(d))


Output:

The type of variable having value 100  is  <class 'int'>

The type of variable having value 187687654564658970978909869576453  is  <class 'long int'>

The type of variable having value 20.345  is  <class 'float'>

The type of variable having value (10+3j)  is  <class 'complex'>


2. String:-

Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote, or triple-quote. In Python there is no character data type, a character is a string of length one. It is represented by str class.

String handling in Python is a straightforward task since Python provides built-in functions and operators to perform operations in the string.


For Example:-

str1 = 'Hello Data Science' #string str1    

str2 = 'Python' #string str2    

print (str1[0:2]) #printing first two character using slice operator    

print (str1[4]) #printing 4th character of the string    

print (str1*2) #printing the string twice    

print (str1 + str2) #printing the concatenation of str1 and str2  

Output:

He
o
Hello Data ScienceHello Data Science
Hello Data SciencePython



3. List:-

Python Lists are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data types whereas a C array can store elements related to a particular data type.

Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type.  

For Example:-

thislist = ["apple", "mango", "banana", "grapes"]

print(thislist)

Output:

['apple', 'mango', 'banana', 'grapes']


4. Tuple:-

Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

For Example:-

Tuple = (25,10,12.5,5,"Hello")

print("Tuple[3] = ", Tuple[3])

Output:

Tuple[3] =  5


5. Dictionary:-

A dictionary in Python is an unordered collection set of data key-value pairs of items like a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. It is like an associative array or a hash table where each key stores a specific value. Key-value is provided in the dictionary to make it more optimized The key can hold any primitive data type, whereas the value is an arbitrary Python object.

The key-value pair items in the dictionary are separated by a colon:, whereas each key is separated with the comma (,) and enclosed in the curly braces {}.

For Example:-

thisdict = {

  "brand": "Kia",

  "model": "Seltos",

  "year": 2023

}

print(thisdict)

Output:

{'brand': 'Kia', 'model': 'Seltos', 'year': 2023}


6. Sets:-

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and has unique elements. In a set, the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various types of values.

For Example:-

thisset = {"potato", "carrot", "radish"}
print(thisset)

Output:

{'carrot', 'radish', 'potato'}

7. Boolean:-

Boolean type provides two built-in values, True and False. These values are used to determine the given statement true or false. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false.  It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error. 

For Example:-

a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a")

Output:

b is not greater than a


SLICING AND INDEXING


Slicing and indexing are two fundamental concepts in Python. They help you access specific elements in a sequence, such as a list, tuple, or string. Let's start looking by Slicing and Indexing.

Slicing:-

Slicing is the process of accessing a sub-sequence of a sequence by specifying a starting and ending index. In Python, you perform slicing using the colon : operator. 

The syntax for slicing is as follows:


sequence[start_index:end_index]


where start_index is the index of the first element in the sub-sequence and end_index is the index of the last element in the sub-sequence (excluding the element at the end_index). To slice a sequence, you can use square brackets [] with the start and end indices separated by a colon.

For Example:-

my_list = ['Bike', 'Car', 'Train', 'Aeroplane']

print(my_list[1:4])

Output:

['Car', 'Train', 'Aeroplane']


Indexing:-

Indexing is the process of accessing an element in a sequence using its position in the sequence (its index).

In Python, indexing starts from 0, which means the first element in a sequence is at position 0, the second element is at position 1, and so on.

To access an element in a sequence, you can use square brackets [] with the index of the element you want to access.

For Example:-

my_list = ['Bike', 'Car', 'Train', 'Aeroplane']

print(my_list[0])

print(my_list[1])

print(my_list[2])

print(my_list[3])

Output:

Bike
Car
Train
Aeroplane









Comments

Popular posts from this blog

ARTIFICIAL INTELLIGENCE (AI) - MACHINE LEARNING (ML) - DEEP LEARNING (DL)

Navigating the GenAI Frontier: Transformers, GPT, and the Path to Accelerated Innovation