0% found this document useful (0 votes)
15 views

Type Conversion in Python

Uploaded by

Arnav Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Type Conversion in Python

Uploaded by

Arnav Rajesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

DAY-5

In Python, type conversion is the process of converting one data type


to another. This can be useful in various situations, such as when you
need to perform operations on variables of different types or when
you want to ensure compatibility between different data types. Here
are some common types of conversions in Python:

1. Implicit Type Conversion (Coercion):


• Python automatically converts one data type to another when an
operation involves two different types.
• For example, adding an integer to a float will result in the integer
being implicitly converted to a float.

2. Explicit Type Conversion (Type Casting):


• You can explicitly convert one data type to another using
predefined functions like `int()`, `float()`, `str()`, etc.
• This is also known as type casting.
3. Conversion between Numeric Types:
You can convert between numeric types using the appropriate casting
functions.

4. Conversion to and from Strings:


Strings can be converted to numeric types and vice versa using
appropriate casting functions.

5. Boolean Type Conversion:


Most values in Python can be evaluated as either True or False in a
boolean context.

2
6. List, Tuple, and Set Conversions:
You can convert between list, tuple, and set types.

Remember that not all conversions are valid, and attempting to


convert between incompatible types may result in errors. It's important
to be aware of the data types you are working with and choose the
appropriate conversion methods accordingly.

Lists in Python
In Python, lists are versatile data structures used to store collections of
items. They are ordered, mutable (modifiable), and allow duplicate
elements. Here are some key points about lists in Python:

1. Declaration: Lists are declared using square brackets `[]` and can
contain elements of different data types.

```

3
2. Accessing Elements: Elements in a list are accessed by their index.
Indexing starts at 0.
```python
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10
```

3. Slicing: You can extract specific portions of a list using slicing.

4. List Operations: Lists support various operations such as appending,


extending, removing, and more.

5. List Comprehensions: Python offers a concise way to create lists


using list comprehensions.

6. Mutability: Lists are mutable, meaning you can change their


elements after they have been created.

4
7. Common List Methods:
• `append()`: Adds an element to the end of the list.
• `insert()`: Inserts an element at a specified index.
• `pop()`: Removes and returns the element at a given index (by
default, the last element).
• `index()`: Returns the index of the first occurrence of a value.
• `len()`: Returns the number of elements in a list.
• extend(): adds one list at the end of another list.
• reverse():Reverses the elements of the list.
• count(): this method counts how many times an element has
occurred in a list
• remove() : it is when we know the element to be deleted , not the
index.

Lists in Python are fundamental and widely used due to their flexibility
and capability to handle various types of data structures efficiently.

Traversing a List
Accessing each element of a list.
a) Using ‘in’ operator inside for loop

L=list(“python”)
for i in L:
print(i)

Here, in operator using for loop iterates each element of a list in


sequence.

5
b) Using range() function range() function can be used for accessing
individual elements of a list, using indexes of elements only, along
with len() method.

L=list(“python”)
n = len(L)
for i in range(n):
print(L[i])

Tuples
In Python, tuples are ordered collections similar to lists, but they have
a few key differences:

1. Immutability: Tuples are immutable, meaning once they are created,


their elements cannot be changed, added, or removed.

2. Declaration: Tuples are declared using parentheses `()` or even


without any brackets, using commas to separate elements.

6
3. Single-element Tuple: If a tuple has only one element, a comma is
required at the end to differentiate it from a simple expression in
parentheses.

4. Accessing Elements: Elements in a tuple are accessed by their index,


just like lists.

5. Tuples are Immutable: As mentioned, tuples cannot be modified


once created. This immutability provides a level of data integrity and
safety for elements within the tuple.

6. Use Cases: Tuples are commonly used for fixed collections of items,
such as coordinates, database records, or any group of related,
immutable data. They can also be used as keys in dictionaries because
of their immutability.

7. Tuple Unpacking: Tuples allow for convenient assignment of


multiple variables in a single line by "unpacking" the tuple's values.

7
8. Functions Returning Multiple Values: Functions can return multiple
values as a tuple, allowing easy extraction of these values.

Tuples serve as useful data structures when you want to store a


collection of items that shouldn't be changed throughout the
program's execution. Their immutability brings a level of integrity to
the data they hold.

Tuple Fucntions
While tuples don't have as many methods as lists due to their
immutability, they do have a few functions and operations that are
available:

1. `count()`: Counts the number of occurrences of a specified element


in the tuple.

2. `index()`: Returns the index of the first occurrence of a specified


element in the tuple.

3. `len()`: Returns the number of elements in the tuple (similar to lists).

8
4. `sorted()`: Creates a sorted list from the elements of a tuple. Since
tuples are immutable, this returns a list.

5. `+` (Concatenation) and `*` (Repetition): Similar to lists, tuples


support concatenation and repetition operations.

6) any() – Returns True if a tuple is having at least one item. If the tuple
is empty it returns False.
Syntx: any(tuple_name)
7) min() - Returns the element with minimum value from the tuple.
Syntax: min(tuple_name)
8) max() – Returns the element with maximum value from the tuple.
Syntax: max(tuple_name)

Accessing and Traversing a Tuple


The individual elements of a tuple can be accessed through their
indexes. Tuples have negative and positive indexes.

9
Traversing a Tuple
a) Using in operator with for loop

tup=tuple(‘python’)
for i in tup:
print(i)
b) Using range()

tup=tuple(‘python’)
n=len(tup)
for i in range(n):
print(tup[i]
Sample Program
1)Write a program to create a list of odd and even numbers from another
list

A)

10
2)
Write a program to fund the maximum and minimum number from a tuple
A)

11

You might also like