0% found this document useful (0 votes)
9 views13 pages

Python List Built

python list and built in function of python

Uploaded by

kumarsharma05990
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
9 views13 pages

Python List Built

python list and built in function of python

Uploaded by

kumarsharma05990
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

Python List Built-in Functions

Python provides the following built-in functions, which can be used with
the lists.

1. len()
2. max()
3. min()

len( )
It is used to calculate the length of the list.

Code

1. # size of the list


2. # declaring the list
3. list1 = [12, 16, 18, 20, 39, 40]
4. # finding length of the list
5. len(list1)

Output:

Max( )
It returns the maximum element of the list

Code

1. # maximum of the list


2. list1 = [103, 675, 321, 782, 200]
3. # large element in the list
4. print(max(list1))

Output:

782

Min( )
It returns the minimum element of the list
Code

1. # minimum of the list


2. list1 = [103, 675, 321, 782, 200]
3. # smallest element in the list
4. print(min(list1))

Output:

103

Let's have a look at the few list examples.

Example: 1- Create a program to eliminate the List's duplicate items.

Code

1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)

Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Example:2- Compose a program to track down the amount of the


component in the rundown.

Code

1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)

Output:

The sum is: 67


In [8]:
Example: 3- Compose the program to find the rundowns comprise of
somewhere around one normal component.

Code

1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)

Output:

The common element is: 2


Python Tuples
A comma-separated group of items is called a Python triple. The ordering,
settled items, and reiterations of a tuple are to some degree like those of
a rundown, but in contrast to a rundown, a tuple is unchanging.

The main difference between the two is that we cannot alter the
components of a tuple once they have been assigned. On the other hand,
we can edit the contents of a list.

Example

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

Features of Python Tuple

o Tuples are an immutable data type, meaning their elements cannot


be changed after they are generated.
o Each element in a tuple has a specific order that will never change
because tuples are ordered sequences.

Forming a Tuple:
All the objects-also known as "elements"-must be separated by a comma,
enclosed in parenthesis (). Although parentheses are not required, they
are recommended.

Any number of items, including those with various data types (dictionary,
string, float, list, etc.), can be contained in a tuple.

Code

1. # Python program to show how to create a tuple


2. # Creating an empty tuple
3. empty_tuple = ()
4. print("Empty tuple: ", empty_tuple)
5.
6. # Creating tuple having integers
7. int_tuple = (4, 6, 8, 10, 12, 14)
8. print("Tuple with integers: ", int_tuple)
9.
10. # Creating a tuple having objects of different data types
11. mixed_tuple = (4, "Python", 9.3)
12. print("Tuple with different data types: ", mixed_tuple)
13.
14. # Creating a nested tuple
15. nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
16. print("A nested tuple: ", nested_tuple)

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))

Parentheses are not necessary for the construction of multiples. This is


known as triple pressing.

Code

1. # Python program to create a tuple without using parentheses


2. # Creating a tuple
3. tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
4. # Displaying the tuple created
5. print(tuple_)
6. # Checking the data type of object tuple_
7. print(type(tuple_) )
8. # Trying to modify tuple_
9. try:
10. tuple_[1] = 4.2
11. except:
12. print(TypeError )

Output:

(4, 5.7, 'Tuples', ['Python', 'Tuples'])


<class 'tuple'>
<class 'TypeError'>

The development of a tuple from a solitary part may be complex.

Essentially adding a bracket around the component is lacking. A comma


must separate the element to be recognized as a tuple.

Code
1. # Python program to show how to create a tuple having a single element

2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses
8. single_tuple = "Tuple",
9. print( type(single_tuple) )

Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Accessing Tuple Elements


A tuple's objects can be accessed in a variety of ways.

Indexing

Indexing We can use the index operator [] to access an object in a tuple,


where the index starts at 0.

The indices of a tuple with five items will range from 0 to 4. An Index Error
will be raised assuming we attempt to get to a list from the Tuple that is
outside the scope of the tuple record. An index above four will be out of
range in this scenario.

Because the index in Python must be an integer, we cannot provide an


index of a floating data type or any other type. If we provide a floating
index, the result will be TypeError.

The method by which elements can be accessed through nested tuples


can be seen in the example below.

Code

1. # Python program to show how to access tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. print(tuple_[0])
5. print(tuple_[1])
6. # trying to access element index more than the length of a tuple
7. try:
8. print(tuple_[5])
9. except Exception as e:
10. print(e)
11. # trying to access elements through the index of floating data type

12. try:
13. print(tuple_[1.0])
14. except Exception as e:
15. print(e)
16. # Creating a nested tuple
17. nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
18.
19. # Accessing the index of a nested tuple
20. print(nested_tuple[0][3])
21. print(nested_tuple[1][1])

Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6

o Negative Indexing

Python's sequence objects support negative indexing.

The last thing of the assortment is addressed by - 1, the second last thing
by - 2, etc.

Code

1. # Python program to show how negative indexing works in Python tuples

2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. # Printing elements using negative indices
5. print("Element at -1 index: ", tuple_[-1])
6. print("Elements between -4 and -1 are: ", tuple_[-4:-1])

Output:

Element at -1 index: Collection


Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')

Slicing
Tuple slicing is a common practice in Python and the most common way
for programmers to deal with practical issues. Look at a tuple in Python.
Slice a tuple to access a variety of its elements. Using the colon as a
straightforward slicing operator (:) is one strategy.

To gain access to various tuple elements, we can use the slicing operator
colon (:).

Code

1. # Python program to show how slicing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Object
s")
4. # Using slicing to access elements of the tuple
5. print("Elements between indices 1 and 3: ", tuple_[1:3])
6. # Using negative indexing in slicing
7. print("Elements between indices 0 and -4: ", tuple_[:-4])
8. # Printing the entire tuple by using the default start and end values.
9. print("Entire tuple: ", tuple_[:])

Output:

Elements between indices 1 and 3: ('Tuple', 'Ordered')


Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection',
'Objects')

Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to
eliminate or remove tuple components as a result.

However, the keyword del can completely delete a tuple.

Code
1. # Python program to show how to delete elements of a Python tuple
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Object
s")
4. # Deleting a particular element of the tuple
5. try:
6. del tuple_[3]
7. print(tuple_)
8. except Exception as e:
9. print(e)
10. # Deleting the variable from the global space of the program
11. del tuple_
12. # Trying accessing the tuple after deleting it
13. try:
14. print(tuple_)
15. except Exception as e:
16. print(e)

Output:

'tuple' object does not support item deletion


name 'tuple_' is not defined

Repetition Tuples in Python


Code

1. # Python program to show repetition in tuples


2. tuple_ = ('Python',"Tuples")
3. print("Original tuple is: ", tuple_)
4. # Repeting the tuple elements
5. tuple_ = tuple_ * 3
6. print("New tuple is: ", tuple_)

Output:

Original tuple is: ('Python', 'Tuples')


New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')

Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are
a few ways to work with tuples in Python. With some examples, this essay
will go over these two approaches in detail.

The following are some examples of these methods.

o Count () Method

The times the predetermined component happens in the Tuple is returned


by the count () capability of the Tuple.

Code

1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. 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 Index() function returns the first instance of the requested element
from the Tuple.

Parameters:

o The thing that must be looked for.


o Start: (Optional) the index that is used to begin the final (optional)
search: The most recent index from which the search is carried out
o Index Method

Code

1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. 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


Utilizing the watchword, we can decide whether a thing is available in the
given Tuple.

Code

1. # Python program to show how to perform membership test for tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordere
d")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)

Output:

True
False
False
True

Iterating Through a Tuple


A for loop can be used to iterate through each tuple element.

Code
1. # Python program to show how to iterate over tuple elements
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Iterating over tuple elements using a for loop
5. for item in tuple_:
6. print(item)

Output:

Python
Tuple
Ordered
Immutable

Changing a Tuple
Tuples, instead of records, are permanent articles.

This suggests that once the elements of a tuple have been defined, we
cannot change them. However, the nested elements can be altered if the
element itself is a changeable data type like a list.

Multiple values can be assigned to a tuple through reassignment.

Code

1. # Python program to show that Python tuples are immutable objects


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
4. # Trying to change the element at index 2
5. try:
6. tuple_[2] = "Items"
7. print(tuple_)
8. except Exception as e:
9. print( e )
10. # But inside a tuple, we can change elements of a mutable object
11. tuple_[-1][2] = 10
12. print(tuple_)
13. # Changing the whole tuple
14. tuple_ = ("Python", "Items")
15. print(tuple_)

Output:
'tuple' object does not support item assignment
('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')

The + operator can be used to combine multiple tuples into one. This
phenomenon is known as concatenation.

We can also repeat the elements of a tuple a predetermined number of


times by using the * operator. This is already demonstrated above.

The aftereffects of the tasks + and * are new tuples.

Code

1. # Python program to show how to concatenate tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Adding a tuple to the tuple_
5. print(tuple_ + (4, 5, 6))

Output:

('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)

Tuples have the following advantages over lists:

o Triples take less time than lists do.


o Due to tuples, the code is protected from accidental modifications. It
is desirable to store non-changing information in "tuples" instead of
"records" if a program expects it.
o A tuple can be used as a dictionary key if it contains immutable
values like strings, numbers, or another tuple. "Lists" cannot be
utilized as dictionary keys because they are mutable.

You might also like