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

Python Lists: Operations and Methods

Python Concepts - Lists

Uploaded by

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

Python Lists: Operations and Methods

Python Concepts - Lists

Uploaded by

Kavitha Donepudi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

UNIT III - LISTS

Dr. [Link]
LISTS
 List is a container that holds a number of items.
 Each element or value that is inside a list is called an item. All the
items in a list are assigned to a single variable.
 Lists can be simple or nested lists with varying types of values.
 Lists are constructed using square brackets [ ] wherein you can
include a list of items separated by commas.
 empty list - list_name = [ ] - item[]
 Lists - store = ["metro", "tesco", "walmart", "kmart", "carrefour"]
 list1 = [4, 4, 6, 7, 2, 9, 10, 15]
 list2 = ['dog', 87.23,’apple’, 65, [9, 1, 8, 1]]
LISTS

 Lists are:
 Ordered - They maintain the order of elements.
 Mutable - Items can be changed after creation.
 Allow duplicates - They can contain duplicate values.
Basic List Operations
 + sign – lists concatenation
 * sign - create a repeated sequence of list items
 1. >>> list_1 = [1, 3, 5, 7]
 2. >>> list_2 = [2, 4, 6, 8]
 3. >>> list_1 + list_2
 [1, 3, 5, 7, 2, 4, 6, 8]
 4. >>> list_1 * 3
 [1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]
 5. >>> list_1 == list_2
 False
 6. >>> 5 in list_1
 True
The list() Function

 The built-in list() function is used to create a list. The syntax for
list() function is, list([sequence])
 where the sequence can be a string, tuple or list itself. If the
optional sequence is not specified then an empty list is created.
 For example,
 1. >>> quote = "How you doing?"
 2. >>> string_to_list = list(quote)
 3. >>> string_to_list
 ['H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']
Indexing and Slicing in Lists
 The syntax for accessing an item in a list is, list_name[index]

 >>> superstore[3]
 'kmart‘
 >>> superstore[-3]
 'walmart'
Modifying Items in Lists
 Lists can be modified.
 >>> fauna = ["pronghorn", "alligator", "bison"]
 >>> fauna[0] = "groundhog“ >>> fauna[-1] = "beaver"
 1. >>> zoo = ["Lion", "Tiger", "Zebra"]
 2. >>> forest = zoo
 Slicing of lists : list_name[start:stop:[step]]
 fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]
 fruits[1:3]
 ['pineapple', 'blueberries']
 >>> fruits[1:4:2]
 ['pineapple', 'mango']
 fruits[::-1]
 ['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
Adding Items to a List
 1. use the append() method to add an element to the end of a Python
list.
 fruits = ['apple', 'banana', 'orange']
 [Link]('cherry')
 print('Updated List:', fruits) -- ['apple', 'banana', 'orange', 'cherry']
 2. insert() method adds an element at the specified index.
 [Link](2, 'cherry')
 print("Updated List:", fruits) -- ['apple', 'banana', 'cherry', 'orange']
 3. use the extend() method to add elements to a list from other list.
 numbers = [1, 3, 5]
 even_numbers = [2, 4, 6]
 [Link](even_numbers)
 print('Updated Numbers:', numbers) -- [1, 3, 5, 2, 4, 6]
Built-In Functions Used on Lists

 len() - The len() function returns the numbers of items in a list.


 sum() - The sum() function returns the sum of numbers in the list.
 any() - The any() function returns True if any of the Boolean values in the
list is True.
 all() - The all() function returns True if all the Boolean values in the list are
True, else returns False.
 sorted() - The sorted() function returns a modified copy of the list while
leaving the original list untouched.
 lakes = ['superior', 'erie', 'huron', 'ontario', 'powell']
 len(lakes)
 lakes_sorted_new = sorted(lakes)
List Methods

 cities = ["oslo", "delhi", "washington", "london", "seattle", "paris", "washington"]


List Methods
 1. >>> dir(list)
 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy',
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Remove an Item From a List

 change the items of a list by assigning new values using


the = operator
 colors[2] = 'Blue
 remove an item from a list using the remove() method.
 numbers = [2,4,7,9] [Link](4) [2, 7, 9]
 del statement removes one or more items from a list.
 del numbers[1] del numbers[:] del numbers del
numbers[1:3]
 Pop statement Returns and removes item present at the given
index – rightmost item.
 Element = [Link](1) [Link]()
Traversing Through a List

 fruits = ['apple', 'banana', 'orange']


 for fruit in fruits:
print(fruit)
for fruit in range(len(fruits))
print(fruit)
print(fruits[fruit])

use the in keyword to check if an item exists in the list.


List Comprehension in Python
 List comprehension offers a concise way to create a new list based on the values
of an existing list.
 numbers = [1, 2, 3, 4]
 square_numbers = [num * num for num in numbers]
 even_numbers = [num for num in range(1, 10) if num % 2 == 0 ]
 even_square_numbers = [num * num for num in numbers if num % 2 == 0 ]
 even_odd_list = ["Even" if num % 2 == 0 else "Odd" for num in numbers]

 List Comprehension with String


 word = "Python"
 vowels = "aeiou"
 result = [char for char in word if char in vowels]
Lambda/Anonymous Function
 lambda : print('Hello World') – created lambda function.
 use the lambda keyword instead of def to create a lambda
function.
 Syntax:
 lambda argument(s) : expression
 hi = lambda : print('Hi.. Hello..')
 hi()
 hi_user = lambda name : print('Hi ..Hello..', name)
 Hi_user(‘kavitha’)
lambda function with map() and
filter()
 The map() function in Python takes in a function and an iterable (lists, tuples, and strings) as
arguments.
 The function is called with all the items in the list, and a new list is returned, which contains
items returned by that function for each item.
 list1 = [1, 5, 4, 6, 8, 11, 3, 12]
 new_list = list(map(lambda x: x * 2 , list1))
 print(new_list)
 Output: [2, 10, 8, 12, 16, 22, 6, 24]
 The filter() function is called with all the items in the list, and a new list is returned, which
contains items for which the function evaluates to True.
 new_list = list(filter(lambda x: (x%2 == 0) , list1))
 print(new_list)
 # Output: [4, 6, 8, 12]
List Comprehensions vs Lambda Functions

 Along with list comprehensions, we also use lambda functions to work with lists.
 While list comprehension is commonly used for filtering a list based on some conditions,
lambda functions are commonly used with functions like map() and filter().
 They are used for complex operations or when an anonymous function is required.
 square_numbers = [num ** 2 for num in numbers]
 square_numbers = list(map(lambda num : num**2 , numbers))
 Program 6.1: Program to Dynamically Build User Input as a List
 list_1 = list(“Enter list items”)
 print(f"List items are {list_1}")
 list_items = input("Enter list items separated by a space ").split()
 print(f"List items are {list_items}")
 items_of_list = []
 total_items = int(input("Enter the number of items "))
 for i in range(total_items):
 item = input("Enter list item: ")
 items_of_list.append(item)
 print(f"List items are {items_of_list}")
 Program 6.2: Program to Illustrate Traversing of Lists Using the
for loop
 fast_food = ["waffles", "sandwich", "burger", "fries"]
 for each_food_item in fast_food:
 print(f"I like to eat {each_food_item}")
 for each_food_item in ["waffles", "sandwich", "burger", "fries"]:
 print(f"I like to eat {each_food_item}")
 Program 6.4: Write Python Program to Sort Numbers in a List in Ascending
Order
 Using Bubble Sort by Passing the List as an Argument to the Function Call
 def bubble_sort(list_items):
 for i in range(len(list_items)):
 for j in range(len(list_items)-i-1):
 if list_items[j] > list_items[j+1]:
 temp = list_items[j]
 list_items[j] = list_items[j+1]
 list_items[j+1] = temp
 print(f"The sorted list using Bubble Sort is {list_items}")
 def main():
 items_to_sort = [5, 4, 3, 2, 1]
 bubble_sort(items_to_sort)
 if __name__ == "__main__":
 main()
Nested Lists
 A list inside another list is called a nested list.
 1. >>> asia = [["India", "Japan", "Korea"],
 ["Srilanka", "Myanmar", "Thailand"],
 ["Cambodia", "Vietnam", "Israel"]]
 2. >>> asia[0]
 ['India', 'Japan', 'Korea']
 3. >>> asia[0][1]
 'Japan'
 4. >>> asia[1][2] = "Philippines"
The del Statement
 You can remove an item from a list based on its index rather than its value. The
difference
 between del statement and pop() function is that the del statement does not return any
value
 while the pop() function returns a value. The del statement can also be used to remove
 slices from a list or clear the entire list.
 1. >>> a = [5, -8, 99.99, 432, 108, 213]
 2. >>> del a[0]
 3. >>> a
 [-8, 99.99, 432, 108, 213]
 4. >>> del a[2:4]
 5. >>> a
 [-8, 99.99, 213]
 6. >>> del a[:]

You might also like