# Lists_tuples.pptx

Lecturer in Computer Science at Sri Sai Baba National Degree College
Jun. 9, 2023
1 of 17

### Lists_tuples.pptx

• 2. M Vishnuvardhan List Lists are used to store multiple items in a single variable. In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ] Eg: fruits = ["apple", "banana", "cherry"] List can be empty or can have different types or can have duplicates Eg: names=[ ] values=[10,”ramu”,35.369,False] numbers=[10,20,30,10,20,30,10,20,30]
• 3. M Vishnuvardhan List – Indexing To access the elements in the list index is used. Index is an integer representing the position of the element in the List. Index always starts from 0 and ends at n-1 Eg: names = ["apple", "banana", "cherry"] names[0] #apple is returned names[4] # Index error names[1.5] # Type Error Python allows negative indexing i.e., -1 refers the last item and -2 represents the last but so on.. (starts at -1 and goes up to –n) names[-1] # cherry is retuned names[-6] # Index error
• 4. M Vishnuvardhan List – Slicing Slicing operator (:) is used to get range of indexes. When specifying a range, the return value will be a new list with the specified items. Syntax listName [ start : end ] # start is inclusive and end is exclusive Eg:fruits=["apple","banana","cherry","orange","kiwi","melon","mango"] fruits[2:5] # returns [“cherry”,”orange”,”kiwi”] # 5 is not included If start is skipped then returns items from beginning fruits[:2] #returns [“apple”,”banana”] If end is skipped then returns items till end . fruits[4:] #returns [“kiwi”,”melon”,”mango”] Slicing allows negative indexing also
• 5. M Vishnuvardhan List – Basic Operations Python Expression Results Description len([1, 2, 3]) 3 Length [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x 1 2 3 Iteration
• 6. M Vishnuvardhan List class methods Function description append() Add an element to the end of the list extend() Add all elements of a list to the another list insert() Insert an item at the defined index remove() Removes an item from the list pop() Removes and returns an element at the given index clear() Removes all items from the list index() Returns the index of the first matched item count() Returns the count of number of items passed as an argument sort() Sort items in a list in ascending order reverse() Reverse the order of items in the list copy() Returns a shallow copy of the list
• 7. M Vishnuvardhan Built-in functions with List 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 a tuple. len() Return the length (the number of items) in the list. list() Convert an iterable (tuple, string, set, dictionary) to a list. max() Return the largest item in the list. min() Return the smallest item in the list sorted() Return a new sorted list (does not sort the list itself). sum() Return the sum of all elements in the list.
• 8. M Vishnuvardhan Tuple A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets. Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed Eg: fruits = ("apple", "banana", "cherry") Tuples can be empty or can have different types or can have duplicates Eg: names=() values=(10,”ramu”,35.369,False) numbers=(10,20,30,10,20,30,10,20,30)
• 9. M Vishnuvardhan List VS Tuple LIST TUPLE Lists are mutable Tuples are immutable Implication of iterations is Time- consuming The implication of iterations is comparatively Faster The list is better for performing operations, such as insertion and deletion. Tuple data type is appropriate for accessing the elements Lists consume more memory Tuple consume less memory as compared to the list Lists have several built-in methods Tuple does not have many built-in methods. The unexpected changes and errors are more likely to occur In tuple, it is hard to take place.
• 10. M Vishnuvardhan Tuple – Indexing To access the elements in the Tuple index is used. Index is an integer representing the position of the element in the List. Index always starts from 0 and ends at n-1 Eg: names = ("apple", "banana", "cherry“) names[0] #apple is returned names[4] # Index error names[1.5] # Type Error Python allows negative indexing i.e., -1 refers the last item and -2 represents the last but so on.. (starts at -1 and goes up to –n) names[-1] # cherry is retuned names[-6] # Index error
• 11. M Vishnuvardhan Tuple – Slicing Slicing operator (:) is used to get range of indexes. When specifying a range, the return value will be a new Tuple with the specified items. Syntax tupleName [ start : end ] # start is inclusive and end is exclusive Eg:fruits=("apple","banana","cherry","orange","kiwi","melon","mango") fruits[2:5] # returns (“cherry”,”orange”,”kiwi”) # 5 is not included If start is skipped then returns items from beginning, If end is skipped then returns items till end .Slicing allows negative indexing also fruits[-6:-3] # returns ("banana","cherry","orange")
• 12. M Vishnuvardhan Tuple – Basic Operations Python Expression Results Description len((1, 2, 3)) 3 Length (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation ('Hi!’)* 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!’) Repetition 3 in (1, 2, 3) True Membership for x in (1, 2, 3): print x 1 2 3 Iteration
• 13. M Vishnuvardhan Tuple class methods Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is create. So no methods for appending, removing , insert elements in tuple. del keyword is used to completely delete the Tuple
• 14. M Vishnuvardhan Unpack Tuples “packing” a tuple means assigning values to the tuple while creation Eg: fruits = ("apple", "banana", "cherry") But Python also allows to extract the values back into variables. This is called "unpacking“ Eg: fruits = ("apple", "banana", "cherry") (a, b, c) = fruits print(a) #returns apple print(b) #returns banana print(c) #returns cherry Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.
• 15. M Vishnuvardhan Unpack Tuples If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list: Eg: fruits=("apple", "banana", "cherry", "strawberry", "raspberry") (a, b, *c) = fruits print(a) #returns apple print(b) #retruns banana print(c) #retruns ['cherry', 'strawberry', 'raspberry']
• 16. M Vishnuvardhan Built-in functions with tuple Function Description enumerate() Return an enumerate object. It contains the index and value of all the items of list as a tuple. len() Return the length (the number of items) in the tuple. tuple() Convert an iterable (list, string, set, dictionary) to a tuple. max() Return the largest item in the tuple. min() Return the smallest item in the tuple sorted() Return a new sorted tuple (does not sort the tuple itself). sum() Return the sum of all elements in the tuple.