Python
- key differences between List and Arrays
- Python collections ChainMap
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python collections
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions in Python
- key differences between List and Arrays
- Program: Calculate Pi in Python
- String Formatting in Python
- Python counters
- python tuples
- Python deque
- Python dictionary
- Python Lists
- python namedtuple
A Python list is a versatile data structure that can store a collection of elements. It allows you to store items of different data types and offers dynamic resizing, making it a preferred choice for various programming tasks.
Creating and Initializing Lists
This section will cover the basic syntax for creating lists and various methods to initialize them with elements.
Empty List:
empty_list = []
another_empty_list = list()
List with Elements:
fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
Using a Loop:
squares = [x**2 for x in range(1, 6)] # Creates a list of the first five square numbers
List Comprehension:
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
Repeating Elements:
zeroes = [0] * 5 # Creates a list with 5 zeroes
Using the range()
Function:
numbers = list(range(1, 6)) # Creates a list of numbers from 1 to 5
Splitting a String:
sentence = "Hello, world!"
words = sentence.split(", ") # Splits the sentence into a list of words
Nested Lists:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Basic Operations on Lists
Learn how to perform fundamental operations on lists, such as finding the length, checking for elements, and slicing.
-
Accessing Elements: You can access individual elements in a list by their index. Remember that Python uses zero-based indexing, so the first element is at index 0.
my_list = [1, 2, 3, 4, 5] first_element = my_list[0] # Access the first element (1) third_element = my_list[2] # Access the third element (3)
</li> <li> <p><strong>Slicing Lists:</strong> You can extract a portion of a list using slicing. Slicing uses the format [start:stop:step], where start is the index to start from (inclusive), stop is the index to stop before (exclusive), and step is the interval between elements.</p> ```py my_list = [1, 2, 3, 4, 5] sub_list = my_list[1:4] # Extracts elements from index 1 to 3: [2, 3, 4] ``` </li> <li> <p><strong>Modifying Elements:</strong> Lists are mutable, so you can change the value of an element by assigning a new value to it.</p>
my_list = [1, 2, 3, 4, 5] my_list[2] = 10 # Changes the third element to 10: [1, 2, 10, 4, 5]
</li> <li> <p><strong>Adding Elements:</strong> You can append elements to the end of a list using the append()method or extend a list by adding elements from another list using the extend()method.</p>
my_list = [1, 2, 3] my_list.append(4) # Appends 4 to the end: [1, 2, 3, 4] my_list.extend([5, 6]) # Extends the list with [5, 6]: [1, 2, 3, 4, 5, 6] ``` <p><strong>Inserting Elements:</strong> You can insert an element at a specific index using the insert() method.</p> <pre><code> my_list = [1, 2, 3, 4, 5] my_list.insert(2, 10) # Inserts 10 at index 2: [1, 2, 10, 3, 4, 5] </pre></code> <p><strong>Removing Elements:</strong> You can remove elements from a list by value using the remove() method, or by index using the pop() method.</p> <pre><code> my_list = [1, 2, 3, 4, 5] my_list.remove(3) # Removes the element with the value 3: [1, 2, 4, 5] popped_element = my_list.pop(2) # Removes and returns the element at index 2 (4) </pre></code> <p><strong>Checking for Existence:</strong> You can check if an element exists in a list using the in operator.</p> <pre><code> my_list = [1, 2, 3, 4, 5] exists = 3 in </pre></code> </ol> <p> my_list # Checks if 3 exists in the list (True)</p> <h3><strong>List Indexing and Slicing</strong></h3> <p>Understand how indexing and slicing work with lists and explore examples of their practical usage.</p> <p><strong>List Indexing:</strong> List indexing is the process of accessing a specific element in a list by specifying its position using an index. In Python, list indexing starts at 0 for the first element.</p> <p>For example, if you have a list my_list, you can access elements as follows:</p> <p>python code :</p> <p><pre><code> my_list = [10, 20, 30, 40, 50] element_at_index_0 = my_list[0] # Access the first element (10) element_at_index_2 = my_list[2] # Access the third element (30) element_at_index_minus_1 = my_list[-1] # Access the last element (50) </pre></code></p> <p>In the above example, my_list[0] retrieves the first element, my_list[2] retrieves the third element, and my_list[-1] retrieves the last element. You can use both positive and negative indices to access elements.</p> <p><strong>List Slicing:</strong> List slicing is the process of extracting a portion (sublist) of a list by specifying a range of indices. Slicing is done using the start:stop:step syntax, where:</p> <ul> <li>start is the index at which the slice begins (inclusive).</li> <li>stop is the index at which the slice ends (exclusive).</li> <li>step is an optional argument that specifies the interval between elements (default is 1).</li> </ul> <p>Here's how list slicing works:</p> <p>python code</p> <p><pre><code> my_list = [10, 20, 30, 40, 50] sublist = my_list[1:4] # Slices from index 1 to 4 (exclusive): [20, 30, 40] sublist_with_step = my_list[0:5:2] # Slices with a step of 2: [10, 30, 50] </pre></code></p> <p>In the first example, my_list[1:4] extracts a sublist that includes elements at indices 1, 2, and 3 but not the element at index 4. In the second example, my_list[0:5:2]slices the list with a step of 2, which means it includes every second element.</p> <h3><strong> Modifying Lists: Adding and Removing Elements</strong></h3> <p>Explore methods to add new elements to lists and techniques to remove elements from lists.</p> Adding Elements: <p>Append: You can add an element to the end of a list using the append() method.</p> <pre><code> my_list = [1, 2, 3] my_list.append(4) # Adds 4 to the end of the list: [1, 2, 3, 4] </pre></code> <p>Extend: To add multiple elements to the end of a list, you can use the extend() method or the += operator.</p> <pre><code> my_list = [1, 2, 3] my_list.extend([4, 5]) # Adds [4, 5] to the end: [1, 2, 3, 4, 5] </pre></code> <p>or</p> <pre><code> my_list += [4, 5] # Adds [4, 5] to the end: [1, 2, 3, 4, 5] </pre></code> <p>Insert: To add an element at a specific index, you can use the insert() method.</p> <pre><code> my_list = [1, 2, 3] my_list.insert(1, 4) # Inserts 4 at index 1: [1, 4, 2, 3] </pre></code> Removing Elements: <p>Remove: You can remove the first occurrence of a specific element using the remove() method.</p> <pre><code> my_list = [1, 2, 3, 2, 4] my_list.remove(2) # Removes the first occurrence of 2: [1, 3, 2, 4] </pre></code> <p>Pop: The pop() method removes and returns an element at a specified index. If the index is not provided, it removes and returns the last element by default.</p> <pre><code> my_list = [1, 2, 3, 4] popped_element = my_list.pop() # Removes and returns the last element (4) element_at_index_1 = my_list.pop(1) # Removes and returns the element at index 1 (2) </pre></code> <p>Del: The del statement can be used to remove an element or a slice of elements by specifying the index or range.</p> <pre><code> my_list = [1, 2, 3, 4] del my_list[1] # Removes the element at index 1: [1, 3, 4] del my_list[1:3] # Removes elements from index 1 to 2 (exclusive): [1, 4] </pre></code> <h3><strong>List Concatenation and Repetition</strong></h3> <p>Discover how to combine multiple lists into one using concatenation and repetition techniques.</p> <h3><strong>Iterating Through Lists</strong></h3> <p>Learn different methods to iterate through lists and process elements efficiently.</p> <h3><strong>List Comprehensions: A Concise Way to Create Lists</strong></h3> <p>Discover the power of list comprehensions for generating lists in a concise and readable manner.</p> <h3><strong>Sorting Lists: In-Place and Sorted Functions</strong></h3> <p>Explore how to sort lists using both in-place sorting methods and the built-in "sorted()" function.</p> <h3><strong>Common List Methods and Functions</strong></h3> <p>This section will cover some commonly used list methods and functions for efficient data manipulation.</p> <h3><strong>Nested Lists: Lists Within Lists</strong></h3> <p>Understand how to create and work with nested lists, enabling more complex data structures.</p> <h3><strong>List vs. Other Data Structures</strong></h3> <p>Compare lists with other data structures like tuples, sets, and arrays to understand their unique use cases.</p> <h3><strong>Best Practices for Using Python Lists</strong></h3> <p>Learn best practices to write clean, Pythonic code using lists effectively.</p> <h3><strong>Performance Considerations</strong></h3> <p>Understand the performance implications of using lists for different tasks and how to optimize code.</p> <h3><strong>Python List Gotchas: Pitfalls to Avoid</strong></h3> <p>Explore common pitfalls and mistakes when working with lists and how to avoid them.</p> ```py def getMedian(lst): sorted_lst = sorted(lst) n = len(sorted_lst) if n % 2 == 0: middle1 = sorted_lst[n // 2 - 1] middle2 = sorted_lst[n // 2] median = (middle1 + middle2) / 2 else: median = sorted_lst[n // 2] return median lst = [10, 50, 75, 83, 98, 84, 32,10] #min value print("min value :",min(lst)) print("max value :",max(lst)) print("mean value :",sum(lst)//len(lst)) print("median value :",getMedian(lst)) #Mode: The most frequent number—that is, the number that occurs the highest number # of times. print("mode value :",max(set(lst), key=lst.count)) from unittest import TestCase class TestListOperations(TestCase): def test_minvalue(self): actual = min(lst) expected = 10 self.assertEqual(actual, expected) def test_value(self): size=len(lst) self.assertTrue(size)