Lecture 3 : List & Tuple in Python | Python Full Course

Lecture 3 : List & Tuple in Python | Python Full Course

Introduction to Python Lists and Tuples

Overview of Chapter 3

  • The video introduces Chapter 3, focusing on lists and tuples in Python, part of a complete series on Python programming.
  • It compares arrays from other programming languages to lists and tuples in Python, explaining that lists are built-in data types for storing sets of values.

Storing Student Marks

  • An example is given where student marks are stored using individual variables (marks1, marks2, etc.), illustrating the limitations when dealing with multiple students.
  • The speaker emphasizes the inefficiency of creating separate variables for each student's marks as class size increases.

Simplifying Data Management with Lists

  • To simplify tracking multiple values, the concept of a list is introduced as a built-in data type that allows storage of multiple values in one variable.
  • A demonstration shows how to create a list by enclosing values within square brackets and separating them with commas.

Working with Lists

Printing and Accessing List Values

  • The speaker demonstrates printing the created list and checking its type using type(), confirming it is indeed a list.
  • Similarities between lists and strings are discussed, particularly indexing which allows access to specific elements within the list.

Indexing Elements in Lists

  • Examples illustrate accessing elements at specific indices (e.g., marks returns the first element).
  • The length of the list can be determined using len(), showcasing how many items are stored.

Differences Between Arrays and Lists

Flexibility in Data Types

  • Unlike arrays in C++ or Java that require uniform data types, Python lists can store mixed data types together (e.g., integers, strings).

Creating Complex Data Structures

  • An example illustrates creating a student information list containing various attributes like name, marks, age, etc., demonstrating flexibility in data management.

Mutability: Key Concept in Python

Understanding Mutability vs. Immutability

Accessing and Modifying Values in Strings and Lists

String Immutability vs. List Mutability

  • Accessing values within strings is allowed, but modifying them (mutation) is not permitted in Python. For example, attempting to assign a new value to the first index of a string will result in an error.
  • In contrast, lists are mutable, meaning their values can be changed after creation. For instance, if we have a list of students, we can change the name at index 0 without any errors.
  • When modifying a list, Python allows for changes without returning an error. This flexibility enables users to print updated lists easily after modifications.

Indexing and Error Handling

  • Lists have defined limits on indexing; accessing an index outside the range results in an "Index out of range" error. For example, trying to access index 3 in a list with only four indices will trigger this error.
  • The valid range for accessing values must be adhered to; otherwise, Python will return an error indicating that the requested index does not exist.

Slicing Mechanism

  • Just like strings, lists support slicing operations where you can extract sublists using starting and ending indices. The end index is exclusive when performing slicing.
  • To create a sublist from a list named 'marks', one would specify the start and end indices (e.g., marks), which returns elements from index 1 up to but not including index 4.

Negative Indexing

  • Lists also support negative indexing similar to strings. Negative indices count backward from the end of the list (e.g., -1 refers to the last element).
  • Using negative indices allows for flexible slicing as well; for instance, marks[-3:-1] would include elements at -3 and -2 but exclude -1.

Introduction to List Methods

  • After covering basic concepts and slicing techniques for lists, it's essential to explore specific methods applicable only to lists rather than general functions used across data types.

Understanding List Operations in Python

Appending Values to a List

  • When appending the value 4 to a list containing [2, 1, 3], the final output becomes [2, 1, 3, 4]. This process is an example of mutation in lists.
  • Mutation refers to changing the values within a list. The append method allows for this change by adding new elements.

Sorting Lists

  • Sorting is crucial in programming and involves arranging items in a specific order. There are two primary types: ascending (smallest to largest) and descending (largest to smallest).
  • For instance, sorting numbers like 0, 1, 2 results in ascending order while reversing it gives descending order.
  • The sort method (list.sort()) sorts the list automatically into ascending order but does not return any value; it returns None.

Understanding Return Values

  • Attempting to print the result of list.sort() will yield None, indicating that no new list is created; instead, the original list is modified directly.
  • After appending 4 and calling sort again, printing the list shows it sorted as expected.

Descending Order Sorting

  • To sort a list in descending order using Python's built-in methods, set reverse=True. It's important to use capital 'T' for True to avoid errors.

Sorting Strings

  • The sort method can also be applied to strings. For example, sorting fruits like "banana", "leech", and "mango" will arrange them alphabetically based on character order.

Reversing Lists

  • The reverse method (list.reverse()) flips the entire list's order without creating a new one. It modifies the original list directly.

Inserting Elements into Lists

Insertion and Removal in Python Lists

Inserting Values into a List

  • To insert the value '5' at index '1', all elements remain unchanged except for the element at index '1', which becomes '5'. The new list will maintain the order of other elements.
  • For example, inserting 'F' at index '1' in the list [2, 1, 3] results in [2, 5, 1, 3], demonstrating how insertion works.

Removing Elements from a List

  • The remove method deletes the first occurrence of an element. For instance, removing '1' from the list [21, 31] will result in a final list without that element.
  • The pop method allows deletion of an element at a specific index. If we want to pop the value at index '2', it removes that particular item while keeping others intact.

Python List Methods Overview

Copying and Counting Elements

  • The copy method creates a duplicate of a list that can be stored in another variable. This ensures all original elements are preserved.
  • The count method counts occurrences of a specific element within the list. Various other methods exist for different functionalities.

Searching for Method Names

  • When programming or developing applications, if you forget an exact method name but know its logic, you can use suggestions from Visual Code or search online resources like googlethalli.com.

Understanding Tuples in Python

Definition and Characteristics

  • A tuple is described as a built-in data type similar to lists but immutable; once created, their values cannot be changed or modified.

Creating Tuples

  • To create tuples, parentheses are used instead of square brackets (used for lists). For example: converting a list to tuple involves simply replacing brackets with parentheses.

Accessing Tuple Elements

  • You can access tuple elements using indices just like lists; however, modifying them directly is not allowed due to their immutable nature.

Working with Single Element Tuples

Creating Single Value Tuples

  • When creating single-element tuples, it's essential to include a comma after the value; otherwise, Python interprets it as just that value's type (e.g., integer).

Empty and Multi-value Tuples

  • An empty tuple can be created by using empty parentheses. Multiple values can also be separated by commas when defining tuples.

Handling Different Data Types in Tuples

Type Recognition by Python

  • If only one value is placed inside parentheses without a comma (like (1)), Python treats it as an integer rather than as a tuple.

Ensuring Tuple Creation with Commas

Tuple Operations and Methods in Python

Understanding Tuple Syntax

  • The use of commas in tuple creation is optional; whether included or not, it does not generate an error. Data will be perceived similarly.
  • Slicing within tuples operates the same way as slicing in lists and strings, allowing for extraction of specific elements.

Tuple Methods

  • Two important methods for tuples are discussed: index and count. The index method finds the first occurrence of an element.
  • Using tuple.index(1) returns the index where the value 1 first appears, demonstrating how to locate elements within a tuple.
  • The count method returns how many times a specified element appears in a tuple. For example, tuple.count(2) would return 1 if 2 appears once.

Practical Application and Problem Solving

  • Lists and tuples function similarly in Python, leading into practice questions based on these concepts.
  • Emphasis is placed on understanding questions before attempting to solve them independently to build logical thinking skills essential for programming.

Programming Exercise: Favorite Movies

  • A task is presented to write a program that prompts users for their three favorite movies and stores them in a list.
  • The approach involves taking inputs sequentially for each movie and appending them to an initially empty list named 'movies'.

Code Implementation Insights

  • After entering movie names, it's crucial to print the final list of movies created from user input.
  • Alternative methods are suggested for appending values directly without needing separate variables for each movie entry.

Next Challenge: Palindrome Check

Palindrome Concepts and Programming Techniques

Understanding Palindromes

  • A palindrome reads the same forwards and backwards, exemplified by "racecar" which remains unchanged when reversed.
  • Lists can also be palindromic; for instance, the list [1, 2, 3, 2, 1] is identical when read from either end.

Checking for Palindromes in Lists

  • To determine if a list is a palindrome, one can utilize the copy method to create a shallow copy of the original list.
  • A shallow copy duplicates the structure of the original list without creating deep copies of nested objects.

Reversing and Comparing Lists

  • The process involves copying an original list and then reversing that copy. If both lists are identical post-reversal, it confirms that the original is a palindrome.
  • For example, if an original list is [1, 2, 3], its reverse will yield [3, 2, 1]. If these two do not match (e.g., [1, 2] vs. [2, 1]), it indicates that it's not a palindrome.

Practical Example of Palindrome Check

  • An example with a non-palindromic list like [1, 2, 3] shows that reversing yields different sequences ([3, 2, 1]), confirming it's not palindromic.
  • If elements were mirrored (e.g., having matching pairs), they would confirm palindromicity upon reversal.

Implementing Palindrome Logic in Code

  • The coding approach involves creating a function to check if an original list matches its reversed version after copying.
  • The code checks equality between the copied reversed list and the original; if they match it prints "palindrome," otherwise "not palindrome."

Counting Students with Grade A

Task Overview

  • The next task requires writing a program to count students who received grade 'A' from given tuples representing grades.

Tuple Creation and Counting Method

  • A tuple named grades will be created containing various student grades including multiple 'A's.
Video description

This lecture was made with a lot of love❤️ Notes : https://drive.google.com/drive/folders/1LahwPSc6f9nkxBiRrz6LFUzkrg-Kzvov?usp=sharing ✨ Instagram : https://www.instagram.com/shradhakhapra/ ✨ LinkedIn : https://www.linkedin.com/in/shradha-khapra/ 0:00 - Introduction 0:51 - Lists in Python 6:28 - Difference between Strings and Lists in Python 9:05 - List Slicing 11:55 - List Methods 22:59 - tuples in Python 23:38 - Difference between Tuples and Lists in Python 27:43 - Tuple Slicing 28:09 - Tuple Method 29:35 - Let's Practice Question 1 34:05 - Let's Practice Question 2 39:47 - Let's Practice Question 3