Introduction to Python Lists and List Comprehension

list list comprehension n.w
1 / 18
Embed
Share

Explore the basics of Python lists and list comprehension in computing, covering concepts like defining lists, list operators, functions, and mutability. Learn how Python supports lists of various data types and how to manipulate them effectively for programming tasks.

  • Python
  • Lists
  • Comprehension
  • Computing
  • Programming

Uploaded on | 2 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. List & List Comprehension

  2. Introduction to Computing Using Python Lists In addition to number, Boolean, and string values, Python supports lists ['ant', 'bat', 'cod', 'dog', 'elk'] [0, 1, 'two', 'three', [4, 'five']] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] A comma-separated sequence of items enclosed within square brackets The items can be numbers, strings, and even other lists >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> >>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk ] >>> >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk']

  3. Introduction to Computing Using Python List operators and functions >>> lst = [1, 2, 3] >>> lstB = [0, 4] >>> 4 in lst False >>> 4 not in lst True >>> lst + lstB [1, 2, 3, 0, 4] >>> 2*lst [1, 2, 3, 1, 2, 3] >>> lst[0] 1 >>> lst[1] 2 >>> lst[-1] 3 >>> len(lst) 3 >>> min(lst) 1 >>> max(lst) 3 >>> sum(lst) 6 >>> help(list ... Like strings, lists can be manipulated with operators and functions Usage x in lst x not in lst lst + lstB lst*n, n*lst lst[i] len(lst) min(lst) max(lst) sum(lst) Explanation x is an item of lst x is not an item of lst Concatenation of lst and lstB Concatenation of n copies of lst Item at index i of lst Number of items in lst Minimum item in lst Maximum item in lst Sum of items in lst

  4. Introduction to Computing Using Python Lists are mutable, strings are not Lists can be modified pets = ['ant', 'bat', 'cod', 'dog', 'elk'] pets = ['ant', 'bat', 'cow', 'dog', 'elk'] Lists can be modified; they are said to be mutable Strings can t be modified Strings can t be modified; they are said to be immutable pet = 'cod' >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pet = 'cod' >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets The elements can be numbers, strings, and even other lists >>> >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> >>> pet = 'cod' >>> >>> pet[2] = 'w' >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> Traceback (most recent call last): File "<pyshell#155>", line 1, in <module> pet[2] = 'w' TypeError: 'str' object does not support item assignment >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk ] >>>

  5. Introduction to Computing Using Python Lists methods len()and sum() are examples of functions that can be called with a list input argument; they can also be called on other type of input argument(s) There are also functions that are called on a list; such functions are called list methods >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 >>> >>> lst.append(7) >>> lst [1, 2, 3, 7] >>> >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 lst.append(7) input argument 7 variable lst refers to a list object ` list method append() Method append()can t be called independently; it must be called on some list object

  6. Introduction to Computing Using Python Lists methods >>> lst = [1, 2, 3] >>> lst.append(7) >>> lst.append(3) >>> lst [1, 2, 3, 7, 3] >>> lst.count(3) 2 >>> lst.remove(2) >>> lst [1, 3, 7, 3] >>> lst.reverse() >>> lst [3, 7, 3, 1] >>> lst.index(3) 0 >>> lst.sort() >>> lst [1, 3, 3, 7] >>> lst.remove(3) >>> lst [1, 3, 7] >>> lst.pop() 7 >>> lst [1, 3] Usage lst.append(item) lst.count(item) Explanation adds item to the end of lst returns the number of times item occurs in lst lst.index(item) Returns index of (first occurrence of) item in lst Removes and returns the last item in lst Removes (the first occurrence of) item from lst Reverses the order of items in lst Sorts the items of lst in increasing order lst.pop() lst.remove(item) lst.reverse() lst.sort() Methods append(), remove(), reverse(), and sort() do not return any value; they, along with method pop(), modify list lst

  7. list.clear() Remove all items from the list. Equivalent to del a[:]. list.extend(iterable) Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable. list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x). list.pop(i) Remove the item at the given position in the list, del list Deletes the list del list[:2] Deletes the first 2 elements of the list List[1:2] = [10,20,30] replaces List[1:2] with the list on right hand side

  8. Introduction to Computing Using Python Exercise List lstis a list of prices for a pair of boots at different online retailers a) You found another retailer selling the boots for $160.00; add this price to list lst b) Compute the number of retailers selling the boots for $160.00 c) Find the minimum price in lst d) Using c), find the index of the minimum price in list lst e) Using c) remove the minimum price from list lst f) Sort list lst in increasing order >>> lst = [159.99, 160.00, 205.95, 128.83, 175.49] >>> lst.append(160.00) >>> lst.count(160.00) 2 >>> min(lst) 128.83 >>> lst.index(128.83) 3 >>> lst.remove(128.83) >>> lst [159.99, 160.0, 205.95, 175.49, 160.0] >>> lst.sort() >>> lst [159.99, 160.0, 160.0, 175.49, 205.95] >>>

  9. Useful Built-in Functions & Tuples Function Description all() Return True if all elements of the list are true (or if the list is empty). any() Return True if any element of the list is true. If the list is empty, return False. enumerate() Return an enumerate object. It contains the index and value of all the items of list as pairs. len() Return the length (the number of items) in the list. max() Return the largest item in the list. min() Return the smallest item in the list sorted() Take elements in the list and return a new sorted list (does not sort the list itself). sum() Return the sum of all elements in the list. list() Convert an iterable (tuple, string, set, dictionary) to a list.

  10. List Comprehensions in Python

  11. List Comprehensions List Comprehensions A list comprehension is a programming language construct for creating a list based on existing lists Why Why comprehension comprehension ? ? The term is borrowed from math s set comprehension notation for defining sets in terms of other sets A powerful powerful and popular Generate a new list by applying a function to every member of an original list popular feature in Python Python s notation: [ [ expression expression for element element in list list ] ] [ expression for element in list ]

  12. List Comprehensions List Comprehensions The syntax of a list comprehension is somewhat tricky >>> L = [x-10 for x in grades if x>0] Syntax suggests that of a for-loop, an in operation, or an if statement All three of these keywords ( for , in , and if ) are also used in the syntax of forms of list comprehensions [ expression for name in list ]

  13. List Comprehensions List Comprehensions >>> li = [3, 6, 2, 7] >>> [elem*2 for elem in li] [6, 12, 4, 14] Note: Non-standard colors on next few slides clarify the list comprehension syntax. [ expressionfor name in list ] Where expression is some calculation or operation acting upon the variable name. For each member of the list, the list comprehension 1. sets name equal to that member, 2. calculates a new value using expression, It then collects these new values into a list which is the return value of the list comprehension. [ expression for name in list ]

  14. List Comprehensions List Comprehensions If list operate correctly on the types of all of list list contains elements of different types, then expression must list members. If the elements of list a container of names matching the type and shape of the list members. list are other containers, then name can consist of list Containers are objects that contain references to other objects (e.g., lists, types, dictionaries) >>> li = [( a , 1), ( b , 2), ( c , 7)] >>> [ n * 3 for (x, n) in li] [3, 6, 21] [ expression for name in list ]

  15. List Comprehensions List Comprehensions expression can also contain user-defined functions >>>defsubtract(a, b): return a b >>> oplist = [(6, 3), (1, 7), (5, 5)] >>> [subtract(y, x) for (x, y) in oplist] [-3, 6, 0] [ expression for name in list ]

  16. Remember Comprehensions Remember Comprehensions Syntax expr for item in iterable if condition expr1 if condition else expr2 for item in iterable >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] >>> L = [ x+1 for x in grades if x<100] >>> L [95, 96, 85, 95, 90, 95] >>> >>> L = [ x+1 if x<100 else x for x in grades] >>> L [96, 97, 100, 86, 96, 91, 96, 100, 100] >>>

  17. Remember Comprehensions Remember Comprehensions Syntax expr1 if cond1 else expr2 for item in iterable if cond2 >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] >>> L = [ x+2 if x<90 else x+1 for x in grades if x<100] >>> L [96, 97, 87, 96, 91, 96] >>>

  18. References Built-in Functions https://docs.python.org/3/library/functions.html Data Structures https://docs.python.org/3/library/functions.html When to Use a List Comprehension in Python https://realpython.com/list-comprehension-python/

More Related Content