Python Lists
- Lists are used to store multiple items in a single variable.
- One of the four built-in data types in Python used to store collections of data (the others are Tuple, Set, and Dictionary).
-
Creating Lists
- Lists are created using square brackets (
[]). - Example:
thislist = ["apple", "banana", "cherry"] print(thislist)
- Lists are created using square brackets (
-
List Properties
- Ordered: Items have a defined order, which doesn’t change unless explicitly altered.
- Changeable: You can add, remove, and modify items after creation.
- Allow Duplicates: Lists can have items with duplicate values.
-
List Items
- Items are indexed: The first item has index
[0], the second[1], and so on. - Example of duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"] print(thislist)
- Items are indexed: The first item has index
-
List Length
- Use
len()to determine the number of items in a list. - Example:
thislist = ["apple", "banana", "cherry"] print(len(thislist))
- Use
-
List Items - Data Types
- List items can be of any data type (string, integer, boolean, etc.).
- A list can even contain mixed data types.
- Examples:
list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3] list3 = [True, False, False] list4 = ["abc", 34, True, 40, "male"]
-
Type of a List
- From Python’s perspective, lists are objects of the data type
'list'. - Example:
mylist = ["apple", "banana", "cherry"] print(type(mylist))
- From Python’s perspective, lists are objects of the data type
-
The
list()Constructor- You can create a list using the
list()constructor. - Example:
thislist = list(("apple", "banana", "cherry")) # note the double round brackets print(thislist)
- You can create a list using the
-
Python Collections (Arrays)
- List: Ordered and changeable. Allows duplicates.
- Tuple: Ordered and unchangeable. Allows duplicates.
- Set: Unordered, unchangeable*, unindexed. No duplicates.
- Dictionary: Ordered** and changeable. No duplicates.
- Notes:
- Set items are unchangeable, but you can add/remove items.
- Dictionaries are ordered as of Python 3.7.
-
Choosing a Collection Type
- Understanding properties of different types is crucial for efficiency, security, and meaning retention.
-
Exercise Example
- What will be the result of the syntax:
mylist = ['apple', 'banana', 'cherry'] print(mylist[1]) - Answer:
banana.
Python List Items:
Access Items by Index
- Indexed access: Use index numbers to access list items. Index starts at 0.
thislist = ["apple", "banana", "cherry"] print(thislist[1]) # Output: "banana" - Note: The first item has index 0.
Negative Indexing
- Access from the end: Negative indexing starts at -1 for the last item.
thislist = ["apple", "banana", "cherry"] print(thislist[-1]) # Output: "cherry" - Examples:
- -1 = Last item
- -2 = Second-last item
Range of Indexes
- Slice a range: Specify start and end indexes for a subset.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) # Output: ['cherry', 'orange', 'kiwi'] - Important Notes:
- Start index is included, end index is not included.
- Start defaults to 0 if omitted.
- End defaults to last item if omitted.
Examples:
# From the beginning to "kiwi" (not included)
print(thislist[:4]) # Output: ['apple', 'banana', 'cherry', 'orange']
# From "cherry" to the end
print(thislist[2:]) # Output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']
Range of Negative Indexes
- Use negative indexes to slice from the end.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[-4:-1]) # Output: ['orange', 'kiwi', 'melon'] - Example: Start at
-4("orange") and end before-1("mango").
Check if Item Exists
- Use the
inkeyword to check if an item is in a list.thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list")
Exercise
What will be the result of the following syntax?
mylist = ['apple', 'banana', 'cherry']
print(mylist[-1])
Answer: cherry.
💥 WordPress https://computerclassinsrilanka.wordpress.com
💥 Facebook https://web.facebook.com/itclasssrilanka
Changing Python List Items
1. Change Item Value
- To change a specific item, use its index:
thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) # Output: ['apple', 'blackcurrant', 'cherry']
2. Change a Range of Item Values
- Replace a range with a new list:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermelon"] print(thislist) # Output: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
3. Insert More Items Than Replaced
- If the new list has more items than the replaced range, the extra items are inserted, shifting the remaining elements:
thislist = ["apple", "banana", "cherry"] thislist[1:2] = ["blackcurrant", "watermelon"] print(thislist) # Output: ['apple', 'blackcurrant', 'watermelon', 'cherry']
4. Insert Fewer Items Than Replaced
- If the new list has fewer items than the replaced range, the remaining elements shift accordingly:
thislist = ["apple", "banana", "cherry"] thislist[1:3] = ["watermelon"] print(thislist) # Output: ['apple', 'watermelon']
5. Insert Items Without Replacing
- Use the
insert()method to add an item at a specific index without replacing existing items:thislist = ["apple", "banana", "cherry"] thislist.insert(2, "watermelon") print(thislist) # Output: ['apple', 'banana', 'watermelon', 'cherry']
Exercise
What will be the result of the following syntax?
mylist = ['apple', 'banana', 'cherry']
mylist[0] = 'kiwi'
print(mylist[1])
Answer: banana.
Explanation:
mylist[0] = 'kiwi'replaces "apple" with "kiwi."- The list becomes
['kiwi', 'banana', 'cherry']. - Printing
mylist[1]outputs the second item, which is"banana".
Key Points on Adding Items to Python Lists
1. Append Items
- Use the
append()method to add an item to the end of the list:thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) # Output: ['apple', 'banana', 'cherry', 'orange']
2. Insert Items
- Use the
insert()method to add an item at a specified index:thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) # Output: ['apple', 'orange', 'banana', 'cherry']
3. Extend List
- Use the
extend()method to append elements from another list:thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) # Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya'] - Note: The elements of the second list are added to the end of the current list.
4. Add Any Iterable
- The
extend()method can also append elements from any iterable object (e.g., tuples, sets, or dictionaries):thislist = ["apple", "banana", "cherry"] thistuple = ("kiwi", "orange") thislist.extend(thistuple) print(thislist) # Output: ['apple', 'banana', 'cherry', 'kiwi', 'orange']
Exercise
What will be the result of the following syntax?
mylist = ['apple', 'banana', 'cherry']
mylist.insert(0, 'orange')
print(mylist[1])
Answer: apple.
Explanation:
mylist.insert(0, 'orange')inserts "orange" at index0.- The updated list becomes
['orange', 'apple', 'banana', 'cherry']. - Printing
mylist[1]outputs the second item, which is"apple".
Key Points on Removing Items from Python Lists
1. Remove a Specified Item
- Use the
remove()method to remove the first occurrence of the specified value:thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) # Output: ['apple', 'cherry'] - If there are duplicate items,
remove()will only remove the first occurrence:thislist = ["apple", "banana", "cherry", "banana", "kiwi"] thislist.remove("banana") print(thislist) # Output: ['apple', 'cherry', 'banana', 'kiwi']
2. Remove an Item by Index
- Use the
pop()method to remove the item at a specific index:thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist) # Output: ['apple', 'cherry'] - If no index is specified,
pop()will remove the last item:thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) # Output: ['apple', 'banana']
3. Remove an Item Using del
- Use the
delkeyword to remove an item at a specific index:thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) # Output: ['banana', 'cherry'] - Use
delto delete the entire list:thislist = ["apple", "banana", "cherry"] del thislist # List no longer exists
4. Clear the Entire List
- Use the
clear()method to empty the list while keeping the list object:thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) # Output: []
Exercise
What is a list method for removing list items?
- Options:
pop()✅push()❌delete()❌
Answer: pop().
Explanation:
pop()is a built-in method for removing items from a list by index.
Looping Through Python Lists
1. Loop Through a List Using for Loop
- You can directly loop through the items in a list:
Output:thislist = ["apple", "banana", "cherry"] for x in thislist: print(x)apple banana cherry
2. Loop Through the List Using Index Numbers
- Use
range()andlen()to loop through items by their index:
Output:thislist = ["apple", "banana", "cherry"] for i in range(len(thislist)): print(thislist[i])apple banana cherry- Here, the range
[0, 1, 2]is created for the list indices.
- Here, the range
3. Loop Through a List Using a while Loop
- Use the
whileloop with the index and the length of the list:
Output:thislist = ["apple", "banana", "cherry"] i = 0 while i < len(thislist): print(thislist[i]) i += 1apple banana cherry
4. Loop Through a List Using List Comprehension
- Use list comprehension for a more concise looping syntax:
Output:thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist]apple banana cherry
Exercise
What is the correct syntax for looping through the items of a list?
Options:
-
for x in ['apple', 'banana', 'cherry']: print(x) ``` ✅ -
for x in ['apple', 'banana', 'cherry'] print(x) ``` ❌ (Missing colon `:`) -
foreach x in ['apple', 'banana', 'cherry'] print(x) ``` ❌ (Python does not use `foreach`)
Answer: Option 1.
Python List Comprehension
1. What is List Comprehension?
- Definition: A shorter syntax to create a new list based on values from an existing list.
- Example (Traditional Approach):
Output:fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist)['apple', 'banana', 'mango'] - Example (Using List Comprehension):
Output:fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist)['apple', 'banana', 'mango']
2. Syntax
newlist = [expression for item in iterable if condition == True]
expression: The item or manipulated version of the item to include in the new list.iterable: The original list, range, tuple, etc., being iterated.condition: (Optional) Filters the items to be included in the new list.
3. Condition
-
Filters the items that evaluate to
True. -
Example: Exclude "apple":
newlist = [x for x in fruits if x != "apple"] print(newlist)Output:
['banana', 'cherry', 'kiwi', 'mango'] -
Condition is Optional: Without a condition:
newlist = [x for x in fruits] print(newlist)Output:
['apple', 'banana', 'cherry', 'kiwi', 'mango']
4. Iterable
-
Any iterable object can be used, e.g., lists, tuples, sets, etc.
-
Example: Use
range():newlist = [x for x in range(10)] print(newlist)Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -
Example with a condition (Numbers less than 5):
newlist = [x for x in range(10) if x < 5] print(newlist)Output:
[0, 1, 2, 3, 4]
5. Expression
-
Manipulate each item in the iteration.
-
Example: Convert to uppercase:
newlist = [x.upper() for x in fruits] print(newlist)Output:
['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO'] -
Example: Set all values to "hello":
newlist = ['hello' for x in fruits] print(newlist)Output:
['hello', 'hello', 'hello', 'hello', 'hello'] -
Example: Use condition in the expression (Replace "banana" with "orange"):
newlist = [x if x != "banana" else "orange" for x in fruits] print(newlist)Output:
['apple', 'orange', 'cherry', 'kiwi', 'mango']
Exercise
Question:
Given the code:
fruits = ['apple', 'banana', 'cherry']
newlist = [x for x in fruits if x == 'banana']
What will be the value of newlist?
Options:
['apple', 'cherry']['banana']✅True
Answer: ['banana']
Key Points on Python - Sorting Lists
1. Sort List Alphanumerically (Ascending by Default)
-
The
sort()method sorts lists alphabetically or numerically in ascending order. -
Example (Alphabetical Sort):
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist)Output:
['banana', 'kiwi', 'mango', 'orange', 'pineapple'] -
Example (Numerical Sort):
thislist = [100, 50, 65, 82, 23] thislist.sort() print(thislist)Output:
[23, 50, 65, 82, 100]
2. Sort in Descending Order
-
Use the keyword argument
reverse=Trueto sort in descending order. -
Example (Descending Alphabetical Sort):
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort(reverse=True) print(thislist)Output:
['pineapple', 'orange', 'mango', 'kiwi', 'banana'] -
Example (Descending Numerical Sort):
thislist = [100, 50, 65, 82, 23] thislist.sort(reverse=True) print(thislist)Output:
[100, 82, 65, 50, 23]
3. Customize the Sort Function
- Use the
key=functionargument to define a custom sort function. - Example (Sort by Distance to 50):
Output:def myfunc(n): return abs(n - 50) thislist = [100, 50, 65, 82, 23] thislist.sort(key=myfunc) print(thislist)[50, 65, 23, 82, 100]
4. Case Sensitivity in Sorting
- By default,
sort()is case-sensitive, placing uppercase letters before lowercase ones. - Example (Case-Sensitive Sort):
Output:thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.sort() print(thislist)['Kiwi', 'Orange', 'banana', 'cherry']
5. Case-Insensitive Sorting
- Use the
key=str.lowerargument to perform a case-insensitive sort. - Example:
Output:thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.sort(key=str.lower) print(thislist)['banana', 'cherry', 'Kiwi', 'Orange']
6. Reverse the Order
- The
reverse()method reverses the current order of list items, regardless of their values. - Example:
Output:thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.reverse() print(thislist)['cherry', 'Kiwi', 'Orange', 'banana']
Exercise
Question:
What is the correct syntax for sorting a list?
Options:
mylist.orderby(0)mylist.order()mylist.sort()✅
Answer:
mylist.sort()
*****************
Key Points on Python - Copying Lists
1. Problem with Direct Assignment
- Direct assignment (
list2 = list1) does not create a new list; instead,list2becomes a reference tolist1. - Changes made to
list1will automatically reflect inlist2.
2. Using the copy() Method
- The
copy()method creates a shallow copy of the list, independent of the original list. - Example:
Output:thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist)['apple', 'banana', 'cherry']
3. Using the list() Method
- The
list()method can also create a new list from an existing one. - Example:
Output:thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist)['apple', 'banana', 'cherry']
4. Using the Slice (:) Operator
- The slice operator (
[:]) creates a copy of the entire list. - Example:
Output:thislist = ["apple", "banana", "cherry"] mylist = thislist[:] print(mylist)['apple', 'banana', 'cherry']
Exercise
Question:
What is the correct syntax for making a copy of a list?
Options:
list2 = list1list2 = list1.copy()✅list2.copy(list1)
Answer:
list2 = list1.copy()
Here are all the points related to joining lists in Python:
-
Using the
+Operator: The easiest way to join two lists is by using the+operator.Example:
list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3)Output:
['a', 'b', 'c', 1, 2, 3] -
Using the
append()Method: Another way to join two lists is by appending each item fromlist2tolist1one by one.Example:
list1 = ["a", "b", "c"] list2 = [1, 2, 3] for x in list2: list1.append(x) print(list1)Output:
['a', 'b', 'c', 1, 2, 3] -
Using the
extend()Method: You can also use theextend()method, which adds elements from one list to another list.Example:
list1 = ["a", "b", "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1)Output:
['a', 'b', 'c', 1, 2, 3]
Exercise Question:
What is a correct syntax for joining list1 and list2 into list3?
Options:
list3 = join(list1, list2)list3 = list1 + list2list3 = [list1, list2]
Correct answer:
list3 = list1 + list2
Here are all the points related to Python list methods:
List Methods in Python:
-
append()
Adds an element at the end of the list.
Example:list1.append(4) -
clear()
Removes all the elements from the list.
Example:list1.clear() -
copy()
Returns a copy of the list.
Example:list2 = list1.copy() -
count()
Returns the number of elements with the specified value.
Example:list1.count(2) -
extend()
Adds the elements of a list (or any iterable) to the end of the current list.
Example:list1.extend([4, 5, 6]) -
index()
Returns the index of the first element with the specified value.
Example:list1.index(3) -
insert()
Adds an element at the specified position.
Example:list1.insert(1, 'a') -
pop()
Removes the element at the specified position and returns it.
Example:list1.pop(2) -
remove()
Removes the item with the specified value.
Example:list1.remove(3) -
reverse()
Reverses the order of the list.
Example:list1.reverse() -
sort()
Sorts the list.
Example:list1.sort()

No comments:
Post a Comment