0% found this document useful (0 votes)
4 views29 pages

Unit 2 (First)

The document provides a comprehensive overview of Python lists, detailing their characteristics, creation, access methods, and various operations such as adding, removing, and modifying elements. It covers list slicing, sorting, and the use of methods like append, extend, and pop, along with examples for clarity. Additionally, it explains list comprehension, counting elements, and basic arithmetic operations involving lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

Unit 2 (First)

The document provides a comprehensive overview of Python lists, detailing their characteristics, creation, access methods, and various operations such as adding, removing, and modifying elements. It covers list slicing, sorting, and the use of methods like append, extend, and pop, along with examples for clarity. Additionally, it explains list comprehension, counting elements, and basic arithmetic operations involving lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

list

• The list data structure/ data type is an ordered


sequence that is mutable and made up of one
or more elements.
• A list can have elements of different data
types such as integer, float, string, tuple or
even another list.
• Elements of a list are enclosed in square
brackets and separated by comma.
• List indexes start from 0.
• Creating a List : To create a list we can use square brackets [] and
separate the elements with commas.
• Eg :
– #create empty and initializing list
– my_list = [1, 2, 3, 4, 5]
– print(my_list)

– list=[]
– print(list)
– print(type(list))
• Accessing a List : To access elements in a list, you can use the
index.
• Eg :
– # Accessing Elements
– print(my_list[0]) # This will print 1
• Try ?????
– My_list[5]
– My_list[-1]
– My_list[n-1]
– My_list[2]=‘Good’
• # Python program to access characters of five
elements of a list.
• st_list = ["Bob", "Mark", "Deepak", "Harry",
"Ivaan"]
• print(st_list[0][1])
• print(st_list[1][1])
• print(st_list[2][3])
• print(st_list[3][0])
• print(st_list[4][4])
• Slicing a List : list slicing is a common practice
and can be used both with positive indexes as
well as negative indexes.
• #access the elements of a list using negative indexing.
– Lst = [50, 70, 30, 20, 90, 10, 50]
– print(Lst[-7::])
• Eg :
– # Initialize list
– List = [1, 2, 3, 4, 5, 6, 7, 8, 9]

– # Show original list


– print("Original List:\n", List)

– print("\nSliced Lists: ")

– # Display sliced list


– print(List[3:9:2])

– # Display sliced list


– print(List[::2])

– # Display sliced list


– print(List[::])
• Eg :
– # Initialize list
– List = ['Nature', 4, 'nature !']

– # Show original list


– print("Original List:\n", List)

– print("\nSliced Lists: ")

– # Display sliced list


– print(List[::-1])

– # Display sliced list


– print(List[::-3])

– # Display sliced list


– print(List[:1:-2])
• # List are incomputable then empty lists are generated.

– List = [-999, 'G4G', 1706256, '^_^', 3.1496]

– # Show original list


– print("Original List:\n", List)

– print("\nSliced Lists: ")

– # Display sliced list


– print(List[10::2])

– # Display sliced list


– print(List[1:1:1])

– # Display sliced list


– print(List[-1:-1:-1])

– # Display sliced list


– print(List[:0:])
Python List Operations Types
• There are many different types of operations that
you can perform on Python lists.
• List are extremely similar to tuples. List are
modifiable(or mutable) i.e. the values can be
changed. Most of the time we use lists not tuples
because we want to easily change the values
• Access the Elements from list :
– To access elements from a list in Python, you can use
square brackets [] along with an index number.
– we can also pass the negative index to access the list
elements in the reverse order (-1 to access the last
element, -2 to access the second last element, and so
on...)
– We can also access a set of elements by using list
slicing by defining the start_index and end_index.
• Eg :
– # declaring lists
– list1 = [10, 20, 30, 40, 50]
– # printing list
– print("list1: ", list1)

– # prints 5 elements from starting


– print("list1[:5]: ", list1[:5])
– # prints 3 elements from starting
– print("list1[:3]: ", list1[:3])

– # prints all elements from the index 0


– print("list1[0:]: ", list1[0:])

– # prints all elements from the index 3


– print("list1[3:]: ", list1[3:])

– # prints the elements between index 2 to 3


– print("list1[2:3]: ", list1[2:3])

– # prints the elements between index 0 to 4


– print("list1[0:4]: ", list1[0:4])

– # prints the elements between index 1 to 4


– print("list1[1:4]: ", list1[1:4])

– # prints elements in the reverse order


– print("list1[ : : -1]: ", list1[ : : -1])
• Add Elements to a List :
– To add an item to the end of the list, use the append() method.
– Eg :
• colors=['red','green','blue']
• colors.append('yellow')
• Colors
– The extend() method is used for adding multiple elements to a list i.e. extend()
take a list as an argument and append all of the elements of the argument list.
you can add any iterable object (tuples, sets, dictionaries etc.).
– Eg :
• fruits=['apple','banana','mango']
• colors.extend(fruits)
• Colors

• list = ["apple", "banana", "cherry"]


• tuple = ("kiwi", "orange")
• list.extend(tuple)
• print(list)
– The insert() method inserts an item at a given position.
– Syntax : list.insert(<pos>,<item>)
– Eg :
• list = ["apple", "banana", "cherry"]
• list.insert(1,'Mango')
• list
• Lists Sorting : this method sorts the items of a list in ascending or
descending order.
• Eg :
– prime_numbers = [11, 3, 7, 5, 2]
– # sorting the list in ascending order
– prime_numbers.sort()
– print(prime_numbers)
• Sort a List in Descending Order : we are sorting the list of numbers
in Descending order, To do this we need to pass reverse=True, this
will sort numbers or the alphabet in descending Order.
• Eg :
– # Sorting list of Integers in descending
– numbers = [1, 3, 4, 2]
– numbers.sort(reverse=True)
– print(numbers)
• Using key Parameter : Use the key parameter to compare each
element of a list and sort it. the built-in len() function that returns
the length of each element and sorts based on the length of each
element.
• Eg :
– cities = ['Mumbai', 'London', 'Paris', 'New York']
– cities.sort(key=len)
– print('List in Ascending Order of the length: ',
cities)
– cities.sort(key=len, reverse=True)
– print('List in Descending Order of the length: ',
cities)
• Update Elements of a List : Python list
provides the following methods to modify the
data.
– list.append(value) # Append a value
– Using slicing
– Eg :
• my_list = [1, 2, 3, 4, 5]
• my_list[1:4] = [6, 7, 8]
• my_list
– list.extend(iterable) # Append a series of values
– list.insert(index, value) # At index, insert value
– list.remove(value) # Remove first instance of value
– list.clear() # Remove all elements
• Remove Elements from a List : The remove() method removes an
element from the list. Only the first occurrence of the same
element is removed in the case of multiple occurrences.
• Eg :
– myList = [1, 2, 3, 'Python', 'makes learning fun!']
– myList.remove('makes learning fun!')
– print(myList)
• The insert() method inserts the specified value at the specified
position.
• Eg :
– fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
• Inserting a Tuple (as an Element) to the List
• Eg :
• mixed_list = [{1, 2}, [5, 6, 7]]
• # number tuple
• number_tuple = (3, 4)
• # inserting a tuple to the list
• mixed_list.insert(1, number_tuple)
• print('Updated List:', mixed_list)
Appending a dictionary to a list

• my_list = [{'name': 'Alice', 'age': 30},


• {'name': 'Bob', 'age': 25}]
• new_dict = {'name': 'Charlie', 'age': 40}

• my_list.append(new_dict)

• print(my_list)
• pop() : The pop() method can remove an element from
any position in the list. If no index is specified then
pop() removes the last item in the list.
• Eg :
– myList = [1, 2, 3, 'Python', 'makes learning fun!']
– myList.pop()
– print(myList)

– myList = [1, 2, 3, 'Python', 'makes learning fun!']


– myList.pop(3)
– print(myList)
• clear() : This function erases all the elements from the list,
set, or dictionary and empties them.
• Eg :
– #This clears all the elements present in the list
– list_one = [100, 150, 200]
– list_one.clear()
– print(list_one)
• the del keyword is used to remove an element from a list or
delete a variable. We can also use del to delete the entire
list.
• Eg :
– # This will remove the element at index 2 (which is 3)
– my_list = [1, 2, 3, 4, 5]
– del my_list[2]
– print(my_list)
• Eg :
– my_list = [1, 2, 3, 4, 5]
– del my_list
– my_list
• Length/Number of Elements in a List:
– The len() method returns the length of the list, i.e., the
number of elements in the list.
– Eg :
• inp = ['Python', 'Java', 'Ruby', 'JavaScript',101,203030.215]
• size = len(inp)
• print(size)
– Using a for loop to get the length of a list :
– Eg :
• inp = ['Python', 'Java', 'Ruby', 'JavaScript',321]
• size = 0
• for x in inp:
• size += 1
• print(size)
• Maximum/Minimum Element within a List :
– The min() method returns the minimum value in the list. The
max() method returns the maximum value in the list. Both
methods accept only homogeneous lists, i.e. lists with similar
elements.
– Eg :
• myList = [0, 2, 3, 44, 5, 6, 7]
• print(min(myList))
• print(max(myList))
• Concatenate Lists :
– The '+' operator can be used to concatenate two lists. It appends
one list at the end of the other list and results in a new list as
output. this method may not be the most efficient for large lists
or two or more lists due to its memory usage.
• Eg :
– list1 = [10, 11, 12, 13, 14]
– list2 = [20, 30, 42]
– res = list1 + list2
– print("Concatenated list:\n",res)
– #print ("Concatenated list:\n" + str(res))
• Using the ‘extend()’ Method :
– The extend() function adds all the elements of a list to the end of the current
list. Unlike the ‘+’ operator, extend() modifies the original list.
• Eg :
– list1 = [10, 11, 12, 13, 14,"A","B","India"]
– list2 = [20, 30, 42]
– list1.extend(list2)
– print(list1)
• List Using List Comprehension method :
– List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list i.e. it is the process of generating a list of
elements based on an existing list.
• Eg :
– fruits = ["apple", "banana", "cherry", "kiwi", "mango","ananas"]
– newlist = []
– for x in fruits:
– if "a" in x:
– newlist.append(x)
– print(newlist)

• Syntax: newList = [ expression(element) for element in oldList if condition ]


• Eg :
– numbers = [1, 2, 3, 4, 5]
– squared = [x ** 2 for x in numbers]
– print(squared)
Eg :
list = [i for i in range(11) if i % 2 == 0]
print(list)
Eg :
n=[m for m in range(1,101)]
print(n)
• Count : The count() method returns the number of elements with the
specified value.
• Eg :
– list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b']
– print(list2.count('b'))
• Count Tuple and List Elements Inside List : we can Count occurrences of
List and Python Tuples inside a list using the Python count() method.
• Eg :
– list1 = [ ('Cat', 'Bat'), ('Sat', 'Cat'), ('Cat', 'Bat'),
– ('Cat', 'Bat', 'Sat'), [1, 2], [1, 2, 3], [1, 2] ]

– # Counts the number of times 'Cat' appears in list1


– print(list1.count(('Cat','Bat')))

– # Count the number of times sublist '[1, 2]' appears in list1


– print(list1.count([1, 2]))
• Multiply / Repetition :
– to multiply two numbers is by using the * operator. This operator works with integers,
floats, and even complex numbers.
• Eg :
– a = 5.5
– b = 3.2
– result = a * b
– print(result)
• Multiplying Lists and Strings
– to repeats the content of list or string for the specified number of times.
• Eg :
– my_list = [1, 2, 3]
– result = my_list * 3
– print(result)
• Eg :
– my_string = "hello"
– result = my_string * 3
– print(result)
• Element-wise Multiplication
– Element-wise multiplication is the process of multiplying corresponding elements of two
arrays or matrices.
• Eg :
– import numpy as np
– array1 = np.array([1, 2, 3])
– array2 = np.array([4, 5, 6])
– result = np.multiply(array1, array2)
– print(result)
• Using the for loop :
– This method uses a for loop to iterate through the
list of numbers.
• Eg :
– # Using a for loop:
– numbers = [1, 2, 3, 4, 5] # Initialize a list of
numbers
– result = 1
– for number in numbers:
– result *= number # Multiply the current number
with the previous result
– print(result)
• Using slicing we can extract a certain length
from the string by using '*' symbol.
• Eg :
– str = 'Python program'
– print(str[7:9]*3)
• Sum: it is not exactly an operator, but rather a
built-in function. It is used to find the sum of
elements in an iterable, such as a list, tuple, or
any other data structure that can be iterated
over.
• Syntax : sum(iterable, start)
• Eg :
– a = (1, 2, 3, 4, 5)
x = sum(a, 7)
• The any() function returns True if any one item in
an iterable are true, otherwise it returns False.
• If the iterable object is empty, the any() function
will return False.
• Eg :
– mytuple = (0, 1, False)
– x = any(mytuple)
– print(x)
• Eg :
– mylist = [False, True, False]
– x = any(mylist)
– print(x)
• Eg :
– from numpy import *
– a=array([100,200,300,400,500])
– b=array([100,20,300,40,500])
– c=a==b
– print(c)
• Eg : using any
– from numpy import *
– a=array([100,200,300,400,500])
– b=array([100,20,300,40,500])
– c=a==b
– print(any(c))
• Eg : using all
– from numpy import *
– a=array([100,200,300,400,500])
– b=array([100,20,300,40,500])
– c=a==b
– print(all(c))

You might also like