0% found this document useful (0 votes)
8 views

List in Python

In Python, a list is a mutable and ordered data structure that can store multiple items of various data types, defined using square brackets. Key characteristics include the ability to change content, allow duplicates, and support indexing. Common operations include adding, removing, and accessing items, as well as list comprehension for creating new lists efficiently.

Uploaded by

thefactquiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

List in Python

In Python, a list is a mutable and ordered data structure that can store multiple items of various data types, defined using square brackets. Key characteristics include the ability to change content, allow duplicates, and support indexing. Common operations include adding, removing, and accessing items, as well as list comprehension for creating new lists efficiently.

Uploaded by

thefactquiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

LIST IN PYTHON

Definition: In Python, a list is a built-in data structure that is used to store


multiple items in a single variable. Lists are ordered, which means the items
have a defined order, and that order will not change unless you modify the list.
Lists are also mutable, meaning you can change their content (add, remove, or
update items) after the list has been created.
Lists can hold items of any data type, including:
 Numbers (integers, floats)
 Strings (text)
 Booleans (True or False)
 Even other lists (nested lists)
Lists are defined using square brackets [ ], and items are separated by
commas.
Syntax: my_list = [item1, item2, item3, ...]
Key Characteristics of Lists:
 Ordered: The items have a fixed order.
 Changeable: You can change the content after creation.
 Allows Duplicates: Lists can have repeated values.
 Index-Based: Each item has a position (index), starting from 0
Examples of Lists in Python
1. A list of numbers:
numbers = [10, 20, 30, 40, 50]
print(numbers)
2. A list of strings:
fruits = ["apple", "banana", "cherry"]
print(fruits)
3. A mixed list:
mixed = [25, "hello", 3.14, True]
print(mixed)
4. Accessing list items:
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
5. Changing an item:
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
6. Adding items:
fruits.append("grape")
print(fruits)
7. Removing items:
fruits.remove("apple")
print(fruits)
8. Looping through a list:
for fruit in fruits:
print(fruit)
9. Nested list
nested = [[1, 2], [3, 4]]
print(nested[1][0]) # Output: 3

Function Description Example

append() Adds item to the end list.append("item")

remove() Removes specified item list.remove("item")

insert() Inserts item at a given position list.insert(1, "item")

pop() Removes item at given index list.pop(2)

len() Returns number of items len(list)

sort() Sorts the list list.sort()

reverse() Reverses the list order list.reverse()

What is a Nested List?


A nested list is a list inside another list.
It is used when you want to store multiple lists together, like a table or matrix
(rows and columns).
Example 1: Basic Nested List
nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list)
This creates a list with 3 inner lists.
Each inner list has 2 numbers.
Accessing Elements in a Nested List
print(nested_list[0]) # Output: [1, 2] → first inner list
print(nested_list[0][1]) # Output: 2 → second item of first inner list
print(nested_list[2][0]) # Output: 5 → first item of third inner list
Example 2: Nested List with Mixed Data
student_info = [
["Alice", 85],
["Bob", 90],
["Charlie", 78]
]
print(student_info[1][0]) # Output: Bob
print(student_info[2][1]) # Output: 78
This structure is often used to store rows of data, like from a spreadsheet or
table.
Example 3: Using Loops with Nested List
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for item in row:
print(item, end=" ")
print() # for new line
Output:
123
456
789
Accessing Items in a List –
Definition: In Python, each item in a list has a specific position, called an
index.
You can access individual items in a list by using their index number inside
square brackets [ ].
 Indexing in Python starts from 0.
o The first item is at index 0
o The second item is at index 1
o And so on...
You can also use negative indexing to access items from the end of the list.
Syntax:
list_name[index]
Example 1: Access by Positive Index
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
Example 2: Access by Negative Index
print(fruits[-1]) # Output: date (last item)
print(fruits[-2]) # Output: cherry (second last item)
Example 3: Using Index in a Loop
fruits = ["apple", "banana", "cherry", "date"]
for i in range(len(fruits)):
print(fruits[i])
apple
banana
cherry
date
This loop prints each item in the list one by one using its index.
Example 4: Accessing Items in a Nested List
nested = [[10, 20], [30, 40], [50, 60]]
print(nested[1]) # Output: [30, 40] → Second inner list
print(nested[1][0]) # Output: 30 → First item of second inner list

Accessing an index that doesn't exist will raise an error:


print(fruits[10]) # IndexError: list index out of range
Would you like me to include a short quiz or worksheet on list indexing for
students to practice?

Modifying a List in Python


Definition: In Python, lists are mutable, which means you can change (modify)
their contents after they are created.
You can:
 Change the value of an existing item
 Add new items
 Remove items
This makes lists very flexible and useful for many tasks.
Ways to Modify a List:
1. Changing Item Value
You can update the value at a specific index using assignment.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
2. Adding Items to a List
Using append() — adds to the end
fruits.append("grape")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'grape']
Using insert() — adds at a specific position
fruits.insert(1, "kiwi")
print(fruits) # Output: ['apple', 'kiwi', 'orange', 'cherry', 'grape']
3. Removing Items from a List
Using remove() — removes by value
fruits.remove("orange")
print(fruits) # Output: ['apple', 'kiwi', 'cherry', 'grape']
Using pop() — removes by index (or last item by default)
fruits.pop(2)
print(fruits) # Output: ['apple', 'kiwi', 'grape']

List Slicing in Python


Definition:
Slicing is a way to access a part of a list (a sub-list) by specifying a range of
indexes.
It helps you extract multiple items from a list at once, rather than one at a time.
Syntax of Slicing:
list_name[start : end : step]
 start: index to begin (included)
 end: index to stop (not included)
 step: how many items to skip (optional)
If step is not provided, it defaults to 1.
Examples of List Slicing
Example 1: Basic Slicing
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # Output: [20, 30, 40]
Starts from index 1 (20) up to index 4 (but not including 60)
Example 2: Omitting Start or End
print(numbers[:3]) # Output: [10, 20, 30] → from beginning to index 2
print(numbers[3:]) # Output: [40, 50, 60] → from index 3 to end
Example 3: Using Step
print(numbers[0:6:2]) # Output: [10, 30, 50] → every 2nd item
Example 4: Negative Index Slicing
print(numbers[-4:-1]) # Output: [30, 40, 50]
Example 5: Reverse a List using Slicing
print(numbers[::-1]) # Output: [60, 50, 40, 30, 20, 10]

Common List Operations with Examples


1. Concatenation (Adding Two Lists)
list1 = [1, 2, 3]
list2 = [4, 5]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5]
2. Repetition
nums = [1, 2]
repeated = nums * 3
print(repeated) # Output: [1, 2, 1, 2, 1, 2]
3. Membership Test (in, not in)
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True
print("grape" not in fruits) # Output: True
4. Length of List
print(len(fruits)) # Output: 3
5. Finding Maximum and Minimum
numbers = [10, 40, 20, 5]
print(max(numbers)) # Output: 40
print(min(numbers)) # Output: 5
6. Sum of List Elements
print(sum(numbers)) # Output: 75
7. Sorting a List
numbers.sort()
print(numbers) # Output: [5, 10, 20, 40]
8. Reversing a List
numbers.reverse()
print(numbers) # Output: [40, 20, 10, 5]

List Methods:
Definition: List methods are built-in functions in Python that can be used to
perform specific actions on lists.
These methods allow you to add, remove, find, sort, and modify list items
directly.
Most list methods change the original list (because lists are mutable), and they
are used by writing:
list_name.method_name(arguments)
Common List Methods with Examples
1. append() – Adds an item to the end of the list
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']
2. insert() – Inserts an item at a specific index
fruits.insert(1, "orange")
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']
3. remove() – Removes the first occurrence of an item
fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'cherry']
4. pop() – Removes and returns the item at the given index (or last item by
default)
fruits.pop()
print(fruits) # Output: ['apple', 'orange']
5. index() – Returns the index of the first matching item
numbers = [10, 20, 30, 20]
print(numbers.index(20)) # Output: 1
6. count() – Returns how many times an item appears
print(numbers.count(20)) # Output: 2
7. sort() – Sorts the list in ascending order
numbers.sort()
print(numbers) # Output: [10, 20, 20, 30]
8. reverse() – Reverses the list order
numbers.reverse()
print(numbers) # Output: [30, 20, 20, 10]
9. clear() – Removes all items from the list
numbers.clear()
print(numbers) # Output: []
10. copy()
Creates a shallow copy of the list (a new list with the same elements).
original = [1, 2, 3]
copied = original.copy()
copied.append(4)
print(original) # Output: [1, 2, 3]
print(copied) # Output: [1, 2, 3, 4]
11. extend()
Adds all items from another list (or iterable) to the end of the list.
list1 = [1, 2, 3]
list2 = [4, 5]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5]
3. sort(reverse=True)
sort() is an option that sorts the list in descending (from largest to smallest)
order.
numbers = [5, 3, 8, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 3, 1]
The list() Function:
Definition: The list() function is a built-in Python function that is used to create
a new list.
You can use it to:
 Convert other iterable data types (like tuples, strings, sets, or dictionaries)
into lists.
 Create an empty list if no argument is provided.
The function takes an iterable as an argument and returns a new list containing
all the elements of that iterable.
Syntax:
list(iterable)
 iterable (optional): Any iterable object like tuple, string, set, etc.
 If you don’t pass any argument, it returns an empty list [].
Examples of list() function
1. Creating an empty list
empty_list = list()
print(empty_list) # Output: []
2. Converting a tuple into a list
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Output: [1, 2, 3]
3. Converting a string into a list of characters
my_string = "hello"
char_list = list(my_string)
print(char_list) # Output: ['h', 'e', 'l', 'l', 'o']
4. Converting a set into a list
my_set = {10, 20, 30}
list_from_set = list(my_set)
print(list_from_set) # Output: [10, 20, 30] (order may vary because sets are
unordered)
5. Using list() with a dictionary
my_dict = {'a': 1, 'b': 2}
list_from_dict = list(my_dict)
print(list_from_dict) # Output: ['a', 'b'] (only keys are converted)

List Comprehension:
Definition: List comprehension is a concise and powerful way to create new
lists by applying an expression to each item in an existing iterable (like a list,
tuple, or range), optionally filtering items with a condition — all in a single line
of code!
It helps make your code shorter, cleaner, and often faster compared to using
traditional loops to build lists.
Syntax:
new_list = [expression for item in iterable if condition]
 expression: The operation or value to add to the new list.
 item: Variable representing each element in the iterable.
 iterable: Any sequence or collection you want to loop through.
 condition (optional): A filter that decides which items to include.
Examples of List Comprehension
1. Create a list of squares
squares = []
for x in range(5):
squares.append(x**2)
print(squares) # Output: [0, 1, 4, 9, 16]
Using list comprehension:
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
2. List of even numbers only
evens = []
for x in range(10):
if x % 2 == 0:
evens.append(x)
print(evens) # Output: [0, 2, 4, 6, 8]
Using list comprehension with condition:
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
3. Convert all strings to uppercase
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names) # Output: ['ALICE', 'BOB', 'CHARLIE']
4. Create list from another list with condition
Get numbers greater than 5 from a list:
nums = [2, 5, 8, 1, 9, 3]
filtered = [num for num in nums if num > 5]
print(filtered) # Output: [8, 9]
5. Nested list comprehension
Flatten a matrix (list of lists) into a single list:
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat) # Output: [1, 2, 3, 4, 5, 6]
6. Using For Loop
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares) # Output: [1, 4, 9, 16, 25]
Using List Comprehension
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
7. For Loop with Condition vs List Comprehension with Condition
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(even_numbers) # Output: [2, 4, 6]
List comprehension:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
8. For Loop (simple)
numbers = []
for i in range(5):
numbers.append(i)
print(numbers) # Output: [0, 1, 2, 3, 4]
List Comprehension (simple)
numbers = [i for i in range(5)]
print(numbers) # Output: [0, 1, 2, 3, 4]
9. Using For Loop with vowels
text = "hello"
vowels = []
for char in text:
if char in "aeiou":
vowels.append(char)
print(vowels) # Output: ['e', 'o']
Using List Comprehension
text = "hello"
vowels = [char for char in text if char in "aeiou"]
print(vowels) # Output: ['e', 'o']
10. Using For Loop with list
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
fruits_with_a = []
for fruit in fruits:
if 'a' in fruit:
fruits_with_a.append(fruit)
print(fruits_with_a)
# Output: ['apple', 'banana', 'date', 'grape']
Using List Comprehension:
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
fruits_with_a = [fruit for fruit in fruits if 'a' in fruit]
print(fruits_with_a)
# Output: ['apple', 'banana', 'date', 'grape']

Example: Extract vowels from each fruit name into a nested list
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
vowels = "aeiou"
vowels_in_fruits = [[char for char in fruit if char in vowels] for fruit in fruits]
print(vowels_in_fruits)
Output:
[['a', 'e'], ['a', 'a', 'a'], ['e'], ['a', 'e'], ['i'], ['a', 'e']]
Fruits list example:
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
1. Reverse the list using reverse() method (in-place):
fruits.reverse()
print(fruits)
Output:
['grape', 'fig', 'date', 'cherry', 'banana', 'apple']
2. Reverse the list using slicing (creates a new reversed list):
reversed_fruits = fruits[::-1]
print(reversed_fruits)
Output:
['grape', 'fig', 'date', 'cherry', 'banana', 'apple']
3. Reverse the list using reversed() function (returns iterator):
reversed_fruits = list(reversed(fruits))
print(reversed_fruits)
Output:
['grape', 'fig', 'date', 'cherry', 'banana', 'apple']
Original list:
fruits = ["apple", "banana", "cherry", "date", "fig", "grape"]
4. Code to reverse list order and reverse each fruit’s letters:
# Reverse the list order and reverse letters of each fruit
reversed_fruits = [fruit[::-1] for fruit in fruits[::-1]]
print(reversed_fruits)
Output:
['eparg', 'gif', 'etad', 'yrrehc', 'ananab', 'elppa']
5. Example
fruits = ["apple", "banana", "cherry"]
reversed_fruits = [fruit[::-1] for fruit in fruits]
print(reversed_fruits)
['elppa', 'ananab', 'yrrehc']
List user through create
1. Integer List
int_list = []
n = int(input("How many integers do you want to add? "))
for i in range(n):
num = int(input("Enter an integer: "))
int_list.append(num)

print("Integer list:", int_list)


List Comprehension:
n = int(input("How many integers do you want to add? "))
int_list = [int(input("Enter an integer: ")) for _ in range(n)]
print("Integer list:", int_list)
2. String List
str_list = []
n = int(input("How many strings do you want to add? "))
for i in range(n):
s = input("Enter a string: ")
str_list.append(s)
print("String list:", str_list)
List Comprehension:
n = int(input("How many strings? "))
str_list = [input("Enter a string: ") for i in range(n)]
print(str_list)

Programs (user define list)


1. Sum of Positive and Negative Numbers in List
n = int(input("How many numbers do you want to add? "))
num_list = [int(input("Enter number: ")) for _ in range(n)]
pos_sum = sum(x for x in num_list if x > 0)
neg_sum = sum(x for x in num_list if x < 0)
print("Sum of positive numbers:", pos_sum)
print("Sum of negative numbers:", neg_sum)
2. Find Maximum and Minimum in the List
n = int(input("How many numbers do you want to add? "))
num_list = [int(input("Enter number: ")) for _ in range(n)]
print("Maximum number:", max(num_list))
print("Minimum number:", min(num_list))
3. Count Even and Odd Numbers in List
n = int(input("How many numbers do you want to add? "))
num_list = [int(input("Enter number: ")) for _ in range(n)]
even_count = sum(1 for x in num_list if x % 2 == 0)
odd_count = n - even_count
print("Even numbers count:", even_count)
print("Odd numbers count:", odd_count)
4. Find Average of Numbers in List
n = int(input("How many numbers do you want to add? "))
num_list = [float(input("Enter number: ")) for _ in range(n)]
average = sum(num_list) / n
print("Average of numbers:", average)
5. Create List and Print Only Unique Elements
n = int(input("How many elements do you want to add? "))
user_list = [input("Enter element: ") for _ in range(n)]
unique_elements = []
for item in user_list:
if item not in unique_elements:
unique_elements.append(item)
print("Unique elements in the list:", unique_elements)
6. Sum of Positive and Negative Numbers in List
n = int(input("How many numbers do you want to add? "))
num_list = [int(input("Enter number: ")) for _ in range(n)]
pos_sum = sum(x for x in num_list if x > 0)
neg_sum = sum(x for x in num_list if x < 0)
print("Sum of positive numbers:", pos_sum)
print("Sum of negative numbers:", neg_sum)
7. Find Maximum and Minimum in the List
n = int(input("How many numbers do you want to add? "))
num_list = [int(input("Enter number: ")) for _ in range(n)]
print("Maximum number:", max(num_list))
print("Minimum number:", min(num_list))
8. Count Even and Odd Numbers in List
n = int(input("How many numbers do you want to add? "))
num_list = [int(input("Enter number: ")) for _ in range(n)]
even_count = sum(1 for x in num_list if x % 2 == 0)
odd_count = n - even_count
print("Even numbers count:", even_count)
print("Odd numbers count:", odd_count)
9. Find Average of Numbers in List
n = int(input("How many numbers do you want to add? "))
num_list = [float(input("Enter number: ")) for _ in range(n)]
average = sum(num_list) / n
print("Average of numbers:", average)
10. Create List and Print Only Unique Elements
n = int(input("How many elements do you want to add? "))
user_list = [input("Enter element: ") for _ in range(n)]
unique_elements = []
for item in user_list:
if item not in unique_elements:
unique_elements.append(item)
print("Unique elements in the list:", unique_elements)
Mixed list (positive, negative, float)
n = int(input("How many numbers? "))
# Create an empty list
num_list = []
# Use a loop to take input n times
for i in range(n):
num = input("Enter a number (can be negative or decimal): ")
# Try converting to int or float
if '.' in num:
num = float(num) # It's a float
else:
num = int(num) # It's an integer
num_list.append(num)
# Print the final list
print("Your number list:", num_list)
Example Output:
How many numbers? 4
Enter a number (can be negative or decimal): 10
Enter a number (can be negative or decimal): -5
Enter a number (can be negative or decimal): 3.14
Enter a number (can be negative or decimal): -7.8
Your number list: [10, -5, 3.14, -7.8]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy