0% found this document useful (0 votes)
52 views20 pages

List

Sequences allow storing multiple values in an organized and efficient manner. There are seven common sequence types in Python: strings, lists, tuples, bytearrays, buffers, xrange objects, and dictionaries/sets for sequential data. Lists are the most flexible and powerful type - they preserve insertion order, allow duplicates, and can contain heterogeneous objects. Lists are created using square brackets and elements can be accessed by integer index.

Uploaded by

Raja Prasant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views20 pages

List

Sequences allow storing multiple values in an organized and efficient manner. There are seven common sequence types in Python: strings, lists, tuples, bytearrays, buffers, xrange objects, and dictionaries/sets for sequential data. Lists are the most flexible and powerful type - they preserve insertion order, allow duplicates, and can contain heterogeneous objects. Lists are created using square brackets and elements can be accessed by integer index.

Uploaded by

Raja Prasant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Sequence Data Type

Sequences allow you to store multiple values in an organized and efficient fashion. Or we can say that A Sequence is
an ordered collection of items, indexed by positive integers. It is a combination of mutable (a mutable variable is one,
whose value can be changed) and immutable (an immutable variable is one, whose value cannot be changed) data
types.

There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.
Dictionaries and sets are containers for sequential data.

Lists
If we want to represent a group of individual objects as a single entity where insertion order preserved and
duplicates are allowed, then we should go for list. Lists are related to arrays of programming languages like C, C ++ or
Java, but Python lists are by far more flexible and powerful than "classical" arrays.

A list is a collection of multiple values stored in a sequence. It is one of the most used datatypes in Python.

All the items in a list do not need to be of the same type. Values in the list are called elements/items.

Lists are mutable and indexed/ordered.

A list is created using square brackets [].

For example, [2, 6, 8, 3, 1] or ["Python", "Java", “C ++”] are both lists.

Each element of the list can be accessed by using it's index number.

The list type is essential for Python scripts and programs; this means that you will hardly find any serious Python
code without a list.

The main properties of Python lists

 Insertion order is preserved


 Duplicate values are allowed
 Heterogeneous objects are allowed (It can be an arbitrary mixture of elements like numbers, strings, and
other lists and so on.)
 Elements of a list can be accessed by an index
 We can differentiate duplicate elements by using index and we can preserve insertion order by using index.
Hence index will play important role.
 List is dynamic because based on our requirement we are increase the size or decrease the size.
 List objects are mutable i.e., we can change the content.
 In list the elements will be placed with square brackets ([]) and with comma () separator.

Creation of the list objects

You can create a list objects In Python programming through various methods given below. You will see that a
list is created by placing all the items (elements) inside a square bracket [], separated by commas they may be of
different types (integer, float, string etc.).

1. We can create empty list object as follows

>>> list = [ ]
>>> print(list)
[]
>>> print (type (list))
<class ‘1ist’ >
2. Create list with elements

>>> list=[10,20,30,40]
>>> print (list)
[10, 20, 30, 40]
>>> list =[‘a’,’b’,’c’,’d’,’e’]
>>> print (list)
[‘a’,’b’,’c’,’d’,’e’]
>>> list=[True, False ]
>>> print(list)
[True, False]

3. Create list with dynamic inputs

# Test.py
list = eval (input ("Enter List:"))
print (list)

Output:

Enter List:[10,20,30,40]
[10, 20, 30, 40]

4. # Creating a List with the use of a String

List = ['You create Your own reality']


print("\n List with the use of String: ")
print(List)

Output:

List with the use of String:


['You create Your own reality']

5. Creating a List with the use of multiple values

List = ["apple", "banana", "Pine"]


print ("\n List containing multiple values: ")
print (List)

Output:

List containing multiple values:


['apple', 'banana', 'Pine']

6. Creating a Multi-Dimensional List (By Nesting a list inside a List)

List = [['Apple', 'Banana'],[‘Onion' , 'Potato']]


print("\n Multi-Dimensional List: ")
print (List)

Output:

Multi-Dimensional List:
[['Apple', 'Banana'], ['Onion', 'Potato'])

7. Creating a List having duplicate values


List=[1, 2, 4, 4, 3, 3, 3, 6, 5]
print ("\n List having duplicate values: ")
print (List)

Output:

List having duplicate values:


[1, 2, 4, 4, 3, 3, 3, 6, 5]

8. Creating a List with mixed type of values

List = [101, 'Akhara', 5.6, True, 1+2j]


print ("\n List with the use of Mixed Values: ")
print (List)

Output:

List with the use of Mixed Values:


[101, 'Akhara', 5.6, True, 1+2j]

9. Create list with list() function

The list() function creates a list in Python.

Syntax: list([iterable])

 Python list() function takes a single argument.


 iterable (Optional) - an object that could be a sequence (string, tuple) or collection (set, dictionary) or iterator
object.

Return value from list(): The list() function returns a mutable sequence list of elements.

 If no parameters are passed, it creates an empty list


 If iterable is passed as parameter, it creates a list of elements in the iterable.

Example:

# empty list
print(list())

# string
s = 'Be a Master'
print (list(s))

# vowel list
List = ['a', 'e', 'i', 'o', 'u']
print(list(List))

Ouput:

[‘B’, ‘e’, ‘ ‘,’a’, ‘ ‘,’M’, ‘a’, ‘s’, ‘t’, ‘e’, ‘r’]

['a', 'e', 'i', 'o', 'u']

10. Create list with split() function

In Python, you may need to break a large string down into smaller strings then we use the split function.
What it does is split a string and add the data to a string array using a defined separator. By default separator is
whitespace.

Syntax: str.split([separator [, maxsplit]])


The split() method takes maximum of 2 parameters:

 separator (optional): This parameter specifies the delimiter character or substring based on which the string will
be split. If not provided, the `split()` method uses whitespace (spaces, tabs, and newlines) as the default
delimiter.
 maxsplit (optional): This parameter specifies the maximum number of splits to be performed. If specified, the
resulting list will have at most `maxsplit + 1` elements. If not provided, all occurrences of the delimiter will be
considered for splitting.

Return Value from split(): The split() breaks the string at the separator and returns a list of strings.

Example 1:: Python code to break the string at the different-different separator point.

Str1 = “Be a Creator”


# splits at space
print (Str1.split())

str2 = "banana, mango, apple"


# splits at ","
print (str2.split(', '))

str3 = “1:2:3:4:5:6:7:8:9”
# Splitting at :
print (str3.split(‘:’))

str4 = "hello world!”


#splitting at ‘@‘
print (str4.split (‘@’))

Example 2: Python code to break the string at the separator point comma(,).

>>x=’0ne, two, three'


>>x. split(‘,’)
>>>a,b,c=x. split (‘,’)
>>> a
'one'
>>> b
' two'
>>> c
'three'

Example 3: Python code to defines the maximum number of splits.

using max-split

nums=’1, 2, 3, 4, 5, 6, 7, 8, 9’
# maxsplit: 2
print (nums.split (‘, ‘, 2 ))

# maxsplit: 1
print (nums.split (‘, ‘, 1 ))

maxsplit: 5
print (nums.split (‘, ‘, 5 ))

# maxsplit: 0
print (nums.split (‘, ‘, 0 ))
Example 4:

grocery = 'banana, orange, mango, apple, pine-apple'

# maxsplit: 2
print (grocery.split (‘, ‘, 2 ))

# maxsplit: 1
print (grocery.split (‘, ‘, 1 ))

maxsplit: 5
print (grocery.split (‘, ‘, 5 ))

# maxsplit: 0
print (grocery.split (‘, ‘, 0 ))
Accessing elements from the List
Indexing

For accessing an element of the list, indexing is used. Each item in a list corresponds to an index number,
which is an integer value, starting with the index number 0 goes to (length -1). So, a list having 5 elements will have
an index from 0 to 4. We can't use float or other types; this will result in TypeError. We can use indexing to change
items within the list, by setting an index number equal to a different value.

We can use the square brackets (index operator []) for slicing along with the index or indices to obtain value
available at that index. Nested list is accessed using nested indexing.

Python supports both positive and negative index.

Positive index: Positive index means starts from left to right (0 to n) (forward direction). The first index has 0; the
next index has 1, and so on. The last index will be the length of the list minus one.

Negative index: Negative index means starts from right to left (- 1to - n) (backward direction).The first index has -1;
the next index has -2, and so on. The last index will be the length of the list.

Example 1: Accessing of element from list using positive index.

lst = ["apple", "banana", "mango"]


print ("Printing list :")
print (lst)
print ("Accessing a element from the list")
print ("lst[0] : ", lst[0])
print (";st[1] : ", lst[1])
print ("lst[2] : ", lst[2])
Example 2: Accessing of element from list using negative index.

lst = ["apple", "banana", "mango"]


print (lst)
print("Accessing a element from the list using -Ve index value")
print ("lst[-1] : ", lst [-1])
print ("lst[-2] : ", lst [-2])
print ("lst[-3] : ", lst [-3])

Note: - The sequentical accesing of each element in a list is called traversing. This can be done by using either for or
while loop statements. In for or while loop statement 'in' operator used to iterate each element of a list in sequence.

Example 3:Accessing of element from list using looping.

lst = ["apple", "banana","mango"]


print("Printing list :")
print (lst)
print ("Accessing a element from the list")
for i in range (0,len(lst)):
print (i,":", lst[i])

Note: In the above program len function is used to find the length of list.

Example 4: Accessing of element from a multi-dimensional list.

lst =[[1,2] , ['mango', 'banana']]

print ("Accessing an element from a multi-dimensional list") 0 1

print('lst[0][0]:', lst [0][0])

print('lst[0][1]:', lst [0][1])


0
1 [ Mango
1 2
Banana ]
print('lst[1][0]:', lst [1][0])

print('lst[1][1]:', lst [1][1])

Slicing
We use indexing to access individual elements but we can use slicing to access a range of items in a list by
using the slicing operator : (colon). Slicing is very useful for extracting certain elements from a list and forms them
into another list, possibly with different number of indices and different index ranges. The syntax for list slicing is as
follows:

seq = L[start : stop :step]

Start->Start position
Stop-->End position
Step-->Increment Specify Step of the Slicing.

o The start, stop, step parts of the syntax are integers.


o Each of them is optional.
o They can be both positive and negative. If you omit first index, slice starts from 0, and omitting of stop will
take it to end. Default value of step is 1.

Example1:
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
10 20 30 40 50 60 70 80 90 100
num=[ 10, 20, 30, 40, 50, 60, 70, 80 ,90,100]

num1= num[3:8]
0 1 2 3 4 5 6 7 8 9
print(numl)

In our example start equals 3, so our slice starts from value 40. stop is 8, so the last element of the slice is 80,
here we are passing +Ve index, then it should be from left to right forward direction (3 to 8 - 1). In the end, slice
creates a new list (we named it num1) with selected elements.

Ouput: (40, 50, 60, 70, 801

Example 2:

num=[ 10, 20, 30, 40, 50, 60, 70, 80 ,90,100]

print (num[:7])

print (num[4:1])

print (num[::])
Output:

[10, 20, 30, 40, 50, 60, 70]


[]
[10, 20, 30, 40, 50, 60, 70, 80 ,90,100]

Note:

1. If index is invalid in indexing process, we get index out of range error, where as in slicing never get index error.

2. In slicing, end index is bigger than 'end index -1', PVM will take up to the last position character only.

Example 3:

num=[10, 20, 30, 40, 50, 60, 70, 80 ,90,100]

print(num[4:70])

print(num[-11:-100])

print(num[-2:10])

print (num[0:10:2]) # Step value 2

Output:

[50, 60, 70, 80, 90, 100]

[90, 100]

[10, 30, 50, 70, 90]

Note:

1. Step value can be +ve or-ve, but cannot be zero otherwise PVM gives an error message.

For example:

>>> print (num [::0])

ValueError: slice step cannot be zero

2. If +ve then it should be from left to right forward direction (0 to (end-1)).

For example:

>>> no = [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> print(no[::1])

[1, 2, 3, 4, 5, -6, 7, 8, 9]

>>> print (no[::2])

[1, 3, 5, 7, 9]

>>> print(no[-6:8])

[4, 5, 6, 7, 8]

3. If-ve then it should be from right to left backward direction (-1 to –(end+1)).

For example:

>>> no = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print (no[::-1])

[9, 8, 7, 6, 5, 4, 3, 2, 1]

>>> print (no[::-2])

[9, 7, 5, 3, 1]

>>> print(no[- 8:- 5])

[2, 3, 4]

4. You can use the shortcuts, for example, if you want every fourth element of a sequence, you need to supply only a
step size of four:

>>> no{::4}

[1,5,9]

Example 4:

>>> no = [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> print (no [::1])

>>> print (no [::2])

>>> print (no [-6:8])

>>> print (no [::-1])

>>> print (no [::-2])

>>> print (no[- 8:- 5])

>>> print (no[1:4:1])

>>> print (no[1:4:-1])

>>> print (no[-1:-9:-1])

>>> print (no [-1:-9:1]

>>> print (no [2:-2:1] )

>>> print (no [-1:2:-1] )

>>> print (no [::-1])

>>> print (no [::1] )

Using range function

To Access the elements from the list, we also use range function. The range() gives a sequence of numbers in
between the two integers given to it. The combination of the for-loop and the range function allow you to build a
traditional numeric for loop:

# Code for print the number from 5 to 10 by using range function

i=5
for i in range (i, 10, 1)
print (i)
# Python program to demonstrate

# Removal of elements in a List

# Creating a List

List = ['G', 'E', 'E', 'K', 'S', 'F','O', 'R', 'G', 'E', 'E', 'K', 'S']

print("Initial List: ")

print(List)

# Print elements of a range

# using Slice operation

Sliced_List = List[3:8]

print("\nSlicing elements in a range 3-8: ")

print(Sliced_List)

# Print elements from a range

# pre-defined point to end

Sliced_List = List[5:]

print("\nElements sliced from 5th element till the end: ")

print(Sliced_List)

# Printing elements from

# beginning till end

Sliced_List = List[:]

print("\nPrinting all elements using slice operation: ")

print(Sliced_List)
# Creating a List

List = ['G', 'E', 'E', 'K', 'S', 'F','O', 'R', 'G', 'E', 'E', 'K', 'S']

print("Initial List: ")

print(List)

# Print elements from beginning

# to a pre-defined point using Slice

Sliced_List = List[:-6]

print("\nElements sliced till 6th element from last: ")

print(Sliced_List)

# Print elements of a range

# using negative index List slicing

Sliced_List = List[-6:-1]

print("\nElements sliced from index -6 to -1")

print(Sliced_List)

# Printing elements in reverse

# using Slice operation

Sliced_List = List[::-1]

print("\nPrinting List in reverse: ")

print(Sliced_List)
Adding Elements to a List
There are following functions used to add Element to the list.

1. append(): In Python, elements can be added to the List by using built-in function append(). Only one element at
a time can be added to the list by using append() method, for addition of multiple elements with the append()
method, loops are used. append() method added of elements at the end of the list.
2. insert(): append() method only works for addition of elements at the end of the List, for addition of element at
the desired position, insert() method is used. Unlike append() which takes only one argument, insert() method
requires two arguments (position, value).
3. extend(): This method is used to add multiple elements at the same time at the end of the list.

Note: append() and extend() methods can only add elements at the end.

Example 1: Addition of elements in a List

1st =[]
print ("Blank List: ")
print (lst)
lst.append(10)
lst.append(30)
lst.append(50)
print ("After Addition of Three elements: ")
print (lst)

Example 2:Adding Multiple elements to the List using loop at the same time

lst =[]
for i in range (10, 20):
lst.append(i)
print("After Addition of elements from 10-19: ")
print(lst)

Example 3: Adding elements to the List to a List

a =[]
for i in range (1, 4) :
a.append(i)
print("\nList after Addition of elements from 1-3:”)
print(a)
b = [‘apple’, ‘boy’]
b.append(a)
print("List after Addition of a List: ")
print (b)

Example 4: Using Insert Method, Addition of Element at specific Position.

lst=[100, 200, 300]


lst.insert(1, 400)
print (lst)
lst.insert (2,"your name")
print(lst)

Example 5: Addition of multiple elements using Extend Method.

lst = [1, 2, 3, 4, 5]
lst.extend ([6, 7, 8])
print ("List after performing Extend Operation: ")
print (lst)

Removing Elements from a List:


There are following functions used to Removing Element from the list.:

1. remove(): The remove() method searches for the given element in the list and removes the first matching
element. If the item present multiple times, then only first occurrence will be removed.
remove() method only removes one element at a time, to remove range of elements, iterator is used.
remove() function raises an Error if element doesn't exist in the set.:

Syntax: list.remove(element):

 The remove() method takes a single element as an argument and removes it from the list.
 If the element(argument) passed to the remove() method doesn't exist, valueError exception is thrown.
 The remove doesn't return any value.

Example 1: If the specified element present in list, remove it.

lst = [10, 20, 30, 40]


print(lst)
lst.remove(30)
print(lst)

Example 2: If the specified element not present in list we will get an error message.

lst = [10, 20, 30, 40]


print (lst)
lst.remove (50)
print (lst)

Example 3:If the item present multiple times then only first occurrence will be removed

lst = [10, 20, 30, 40, 20]


print (lst)
lst.remove (20)
print (lst)

2. pop(): pop() function can also be used to remove and return an element from the set, but by default it
removes only the last element of the set, to remove element from a specific position of the List, index of the
element is passed as an argument to the pop() method.

Syntax: list.pop(index)

 The pop() method takes a single argument (index) and removes the item present at that index.
 If the index passed to the pop() method is not in range, it throws IndexError: pop index out of range
exception.
 The parameter passed to the pop() method is optional. If no parameter is passed, the default index -1 is
passed as an argument which returns the last item.

Example 1:

lst = [10,20,30]
print (lst)
lst.pop()
print (lst)
lst.pop()
print (lst)
lst.pop()
print (lst)

Example 2: If the list is empty then pop() function raises an error message.

lst =[]
print(lst)
lst .pop()

Difference between remove() and pop():

remove() Pop()
pop() takes an index as its argument and will remove the element
remove() takes an element as its argument
and removes it if it's in the list, otherwise an at that index. If no argument is specified, pop will remove the last
exception will be thrown. element. pop() also returns the element it removed.

remove () it delete the matching pop removes the element at a specific index or by default last
element/object. element.
It can't return any value. It returned remove element.
It throws value error in case of value doesn't
It throws index error in case of an index doesn't exist in the list.
exist in the list
Note: List objects are dynamic i.e., based on our requirement we can increase and decrease the size.

1. append(), insert(), extend(): for increasing the size.


2. remove(), pop(): for decreasing the size.
3. clear() function: We can use clear() function to remove all elements of list.

Example:

>>>x=[‘a' , ‘b’, ‘c’]

>>>print(x) # To print the List

[‘a' , ‘b’, ‘c’]

>>>x. clear() # To clear the List

>>>print(x)

[]

del statement:-It is used to remove specific items from the list or to remove all items identified by a slice. To delete a
single element from a python list, use its index and use the slicing operator to delete a slice.

The syntax is:-

del list[m] # To delete single element

del list[m:n] # To delete multiple element.

Example:

>>>name=['amit', 'sumit', 'raj', 'rahul']


>>>del name[2] #Deleting a single element from the name list.
>>> print (name)
['amit', 'sumit', 'rahul']

To delete multiple elements from the middle of a list.

>>>name=['amit', 'sumit', 'raj', 'rahul', 'suresh', 'ramesh']


>>>del name[1:4] # Deleting the few element
>>>name
['amit', 'suresh', 'ramesh']

To delete the entire python list


>>>del name #Deleting the entire python list.

Ordering elements of List


There are following ways to change the order of elements in the list.

1. sort(): The sort() method sorts the elements of a given list in a specific order - Ascending or Descending. It
doesn't return any value.

Syntax: list.sort()
or
list.sort(key=..., reverse =...)
In the above syntax:

 key- To specify a function (or other callable) to be called on each list element prior to making comparisons.
 reverse- If true, the sorted list is reversed (or sorted in Descending order)

Example 1:
>>> x = [2, 5, 3, 90, 12, 67]
>>> x. sort ()
>>> X
[2, 3, 5, 12, 67, 90]
>>> x = [3, 2, 5, 1, 4]
>>>y=x.sort() # Don't do this!
>>>print (y)
None

Since sort () modifies x but returns nothing, you end up with the sorted and the y containing None. One correct
way of doing this would be to first bind y to a copy of x, and then sort y, as shown below:

>>> x = [3, 2, 5, 1, 4]
>>>y=x[:] # x [:] is a slice containing all the elements of x, effectively a copy of the entire list.
>>>y.sort()
>>>x
[3, 2, 5, 1, 4]
>>>y
[1, 2, 3, 4, 5]

If the Python list members are strings, it sorts them according to their ASCII values.
>>>y = ['zebra', 'pink', 'apple', 'boy']
>>> y.sort()
>>> print (y)
['apple', 'boy', 'pink', 'zebra']
>>> print (y.sort()) #sort() doesn't return any value, so that none is the result.
None

Example 2: key=len sorts the strings by length.


>>>str=['aaaa', 'bb', 'd', 'ccc']
>>>str.sort(key=len)
>>>print (str)
['d', 'bb', 'ccc', 'aaaa']
Here, len is the Python's in-built function to count the length of an element. The list is sorted based on the length
of each element, from lowest count to highest.
Example 3: reverse=True sorts the list in the descending order.
nums [70,50,60,1,20]
print ("Original list : ", nums)
nums.sort(reverse=True)
print ('Sorted (Descending order) list:, nums)

Output:
Original list : [70, 50, 60, 1, 20]
Sorted (Descending order) list: [70, 60, 50, 20, 1]

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

2. sorted():-It takes two three parameters:-


Syntax: sorted(iterable[, key][, reverse])
 iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator.
 reverse (Optional) - If true, the sorted list is reversed (or sorted in Descending order).
 key (Optional) - function that serves as a key for the sort comparison.
 This method returns a sorted list from the given iterable.

Example 4:
nums=[70,50, 60,1,20]
print ("Original list : ", nums)
print('Sorted (Ascending order) list:’, sorted (nums))

Output:
Original list: [70, 50, 60, 1, 20]
Sorted (Ascending order) list: [1, 20, 50, 60, 70]

Example 5: reverse=True sorts the list in the descending order.


nums =[70, 50, 60, 1, 20]
print ("Original list : ", nums)
print ('Sorted (Descending) list:’, sorted (nums, reverse=True))

Output:
Original list: [70, 50, 60, 1, 20]
Sorted (Descending) list: [70, 60, 50, 20, 1]

Note: In Python 2 if list contains both numbers and strings then sort() function first sort numbers and followed by
string. But in Python 3 it is invalid.

Example 6: If list contains both numbers and strings then sort() and sorted() raises an error message.
nums=['apple', 50, 60, 'banana", 20]
print("Original list : ", nums)
nums.sort()
print('Sorted list : ‘, nums)

Output:
Original list: ['apple', 50, 60, 'banana', 20]
Traceback (most recent call last):
File "C:/Python37/practice/test.py", line 3, in <module>
nums.sort()
TypeError: '<' not supported between instances of int' and 'str'

Note:

 Both list.sort() and sorted() have a key parameter to specify a function.


 Difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable
list.
3. reverse:We can use reverse() method to reverses the order of Items/elements in the list. The reverse
function doesn't take any argument. The reverse() function doesn't return any value. It only reverses the
elements and updates the list.
Syntax: list.reverse()
Example 1:
Lst=[10,20,30,40]
print ("Before reversing list items")
print (lst)
lst.reverse()
print ("After reversing list items")
print (lst)
Output:
Before reversing list items
[10, 20, 30, 40]
After reversing list items
[40, 30, 20, 10]
Example 2:
Ist =[‘a’,‘b’,‘c’,‘d’]
print("Before reversing list items")
print(lst)
lst.reverse()
print ("After reversing list items")
print (lst)
output:
Before reversing list items
[‘a’,‘b’,‘c’,‘d’]
After reversing list items
[‘d’,c’,’b’,’a’]
4. reversed()-If you need to access individual elements of a list in reverse order, it's better to use reversed
method. reversed() method returns an iterator that accesses the given sequence in the reverse order.
Syntax: reversed(sequence)
Example: Python code to demonstrate working of 'reversed()' function.
#For string
str=’god’
print (list (reversed (str)))
For tuple
tpl = ( ^ 2 * m ^ 2, 1a ^ 2 , 'a', ' t', 'e', '') print (list (reversed (tpl)))::#For range::rng = range(1,
5)::print(list(reversed(rng)))::plus/minus 5 * or *
11st 1st = [1, 2, 4, 3, 5]::print(list(reversed(lst)))::I'd', x
'o', 'g'l::Output:::[^ prime Sigma' ,^ prime e^
1030 20 ‘zero’ ‘one’
prime ,^ prime Sigma^ prime ,^ prime B^ prime ,^
prime ]::14, 3, 2, 11 [ 5, 3, 4, 2, 1::To Reverse a List y
Using Slicing Operator::Example:::1st = ['a', 'b', 'c',
'd' ]::print ("Before reversing list items")::print (1st)::Ist =Ist[::-1]::print ("After reversing list items") print
(1st)::output:::Before reversing list items::\ ^ * a ^ * ,&b^ * ,&c^ * ,&d^ * \ After reversing list items::('d', 'e',
'b', 'a'l::5.1.7 List Accessing Methods::Python provides various List access methods that operate on list. For
example,::index():-It returns the index of first occurrance, Start and End index are not necessary
parameters.:Syntax:-::List.index( element [,start[,end]])::Example:-::>>> List = [1, 2, 3, 1, 2, 1, 2, 3, 2,
1]::>>>print(List.index(2)) #output 1::1::>>>print(List.index (2, 2) ) #It returns the second position of element
2.::4::2.max(list): It returns an item from the list with max value.::Syntax:-max(list_Var)::3.min(list): It returns
an item from the list with min value.::Syntax:-min(list_Var)::Example:-::>>> list = [22, 11, 44, 22, 21]::>>>
print (max(list))::44::>>>print(min(list))::11::>>>X=[10,12,13,15]::>>>y=[10,12,13,15,16]
>>>print(min(x,y))::>>>print(max(x,y)) [10, 12, 13, 15, x

10 20 ‘zero’ ‘one’
y
16]::[10, 12, 13, 15]::4. count(obj):-It returns count of how many times obj occurs in list.::Syntax:-
List.count(obj)::Example:-::>>> list = [22, 11, 44, 22, 21]::>>>list. count(22)::2:5.1.8 Aliasing and Cloning of
List objects::The process of giving another reference variable to the existing list is called aliasing. Example
1::x=[10,20, prime zer * o' ,^ prime one^ prime ]::y = x::print ("id of x:", id (x))::print ("id of y : ", id
(y))::Output:::id of x:::45409664::id of y:::45409664:The problem in this approach is by using one reference
variable if we are changing content, then those changes will be reflected to the other reference
variable.:Example 2:::x=[ 10, 20 , ' zer * o' , 'one']::y = x::print ("id of x: "::, id (x)) print ("id of y: ", i *
d(y) )::y[0] = 30::print (y)::print (x)::Output:::id of x: 45606272::45606272 id of y: 45606272::[30, 20, 'zero',
'one'] zero', ' one']::[30, 20, ':To overcome this problem we should go for cloning. The process of creating
exactly duplicate independent object is called cloning. We can implement cloning by using slice operator or
by using copy function.:Example 3: By using slice operator::x = [10, 20, 30]::y =x[:]::print ("id of x: ", id
(x))::print ("id of y: ", id (y))::y[1] = 15::print (y)::print (x)::id of x: 45409544::Output:::id of y: 45409224::[10,
15, 30] [10, 20, 30]::Example 4:::by using copy() function::x = [10, 20, 30] y=x. copy ()::print ("id of x: ", id(x))
print("id of y: ", id (y))::y[1] = 15::print (y)::print (x)::Output:::id of x: 45147360::Lid id of y: 45147040 [10, 15,
30]::[10, 20, 30]:Note: Difference between '=' operator and copy() function: '=' operator meant for aliasing
and copy function meant for cloning(). 5.1.9 Using mathematical operators for
list objects In Python, we can use '+' and '*' operators for list
objects.:Concatenation operator(+): We can use '+' operator to
concatenation 2 lists into a single list.::Example:::x = [10, 20, 30] y = [40,
50, 60]::z = x + y print(z)::Output: [10, 20, 30, 40, 50, 60]::Note: To use
'+' operator compulsory both arguments should be list type objects, otherwise we will get TypeError
message.::Example:::>>> x = [10, 20]::>>> y = x + 20 marble maps Ballestado Traceback (most recent call
last):::File "<pyshell#85", line 1, in <module>::y = x + 20::TypeError: can only concatenate list (not "int") to list
>>> y = x + [30]::[10, 20, 30]::2. Repetition operator (*): We can use repetition operator to repeat elements of
list specified::number of times.::x = [10, 20, 30]::z = x + 3::Example:::print(z)::Output:::[10, 20, 30, 10, 20,::30,
10, 20, 30]::5.1.10 Comparing list objects::We can use comparison operators for list objects.::Example 1:::x =
[10, 20, 30]::y = [10, 20, 30] z = [20, 30, 10] print ( x ==z)::print (x==v)::pzint(x! = z)::Output:::True::False
True::be considered.::il vol a Note: Whenever we are using comparison operators (==,!=) for list objects then
the following should::The number of elements.:The order of elements.:The content of elements (case
sensitive).:Example:::x=[^ prime a' ,^ prime b^ prime ,^ prime c^ prime ] y=[^ prime a' ,^ prime b^ prime ,^
prime c^ prime ] z=[^ prime A' ,^ prime B^ prime ,^ prime C^ prime ]::print ( x ==y) vrint (x==z)::print (x! =
z)::Output:::True::False::True::Note: whenever we are using relational operators (<,<=,>,>=) between list
objects, Then only first element comparison will be performed.::Example:::x=[^ prime a' ,^ prime b^ prime ,^
prime c^ prime ]::y=[^ prime a' ,^ prime b^ prime ,^ prime c^ prime ]::z=[^ prime A' ,^ prime B^ prime ,^
prime C^ prime ]::print(x > y)::print (x >= z)::print(x < z)::print(z <
x)::Output:::False::True::False::True::Membership Operator for list objects::5.1.11::In Python, we can check
whether element is a member of the list or not by using membership operators. Membership operators are
'in' and 'not in'. Python's membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below-
X===> 10 20 30
Operator Description Example
Y===> 10 It 20
In 15 30
evaluates to true if it finds a variable in the x in y, here if x is a member of sequence y.
specified sequence and false otherwise. Then results will be 1.
not in It evaluates to true if it does not finds a Ivariable in x not in y, here if x is not a member of
the specified sequence and false otherwise. sequence y. Then results will be 1.
Example:::x=[^ prime a' ,^ prime b^ prime ,^ prime c^ prime ]::print (^ prime a' * inx )::print (^ prime d' *
inx )::print('b' not in x) print('e' not in x):Output:::True::False::False::True:5.1.12 Nested Lists:Sometimes we can take
one list inside another list. Such types of lists are called nested lists. :Example: :a = [10, 20, [30,
40]] :print (a) :print (a[0]) :print (a[1]) :print (a[2]) :print (a[2][0]) :print (a [2]
[1]):Output::[ 10, 20, [30, 401]:10::20 [30, 40] 30 40:Note: We can access nested list elements by using index just like
accessing multidimensional array elements. In Python, we can represent matrix by using nested lists.:Example:::a =
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]::print (a)::print ("printing elements by row wise")::for i in a:::print (i)::print ("printing
elements by matrix style") for i in range (len (a)) :::for i in range (len (a[i])): print (a[i][j], end="") print():Output:::[[1,
2, 3], [4, 5, 6], [7, 8, 9]]::printing elements by row wise::[1, 2, 3]::[4, 5, 6]::[7, 8, 9]::printing elements by matrix
style::1::2 3::4 5 6::7 8 9:5.1.13 Comprehension::Comprehensions in Python provide us with a short and concise way
to construct new sequences (list, dictionary, set and generator) using sequences which have been already
defined.::5.1.13.1 List comprehension::List Comprehensions provide an elegant way to create new lists. The following
is the basic structure of a list comprehension: output_list = [output_expression for var in input_list if (var satisfies this
condition)]::Note: The list comprehension may or may not contain an if condition. List comprehensions can contain
multiple for (nested list comprehensions).::Example: Suppose we want to create an output list which contains
squares of all the numbers from 1 to 10.::list =[]::for a in range (1, 11):::list.append ( a **2) print ("Output : ", list)
print (type (list))::Output:::Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] <class 'list'>::::

You might also like