0% found this document useful (0 votes)
7 views11 pages

What Are Python Lists

Uploaded by

patodiabarsha
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)
7 views11 pages

What Are Python Lists

Uploaded by

patodiabarsha
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/ 11

What are Python Lists?

A list in Python is an ordered, mutable collection of items. Enclosed in square brackets, they are incredibly versatile, allowing you to
store a sequence of elements.

Ordered Mutable Flexible


Elements maintain their insertion Lists can be changed after creation: They can contain a mix of different
order and are indexed, starting from add, remove, or modify elements. data types (integers, strings,
0. booleans, etc.).
Creating Your First List
There are a few straightforward ways to initialize lists in Python. You can directly declare them with square brackets or convert
other iterables.

Direct Declaration Mixed Data Types


The most common method involves placing comma-separated Lists embrace diversity! You can combine various data types
items inside square brackets. within a single list.

fruits = ["apple", "banana", "cherry"] mixed_list = ["Alice", 3.14, True]

Using `list()` Constructor


numbers = [10, 20, 30, 40]
Convert other iterable types like tuples into lists using the list()
constructor.

numbers = list((1, 2, 3))


Accessing List Elements
Lists are ordered, meaning each element has a specific position, or index. You can access individual items or subsets of items using
indexing and slicing.

Indexing Slicing
Access elements by their position (index). Python uses zero- Extract a portion of a list using slicing. This creates a new list
based indexing, so the first element is at index 0. without modifying the original.

lst = [10, 20, 30, 40, 50] print(lst[1:4])

print(lst[0]) Output: [20, 30, 40]


Output: 10
print(lst[::-1])
print(lst[-1]) Output: [50, 40, 30, 20, 10] (reversed list)
Output: 50 (last element)
Modifying Lists: Adding and Updating
As mutable objects, lists allow you to change their content after creation. You can update existing elements or add new ones.

Updating Elements Adding Elements


Change the value of an element by assigning a new value to its append(): Adds an item to the end of the list.
index. insert(): Adds an item at a specific index .

extend(): Appends elements from another iterable (like


my_list = [10, 20, 30, 40]
another list) to the end.

my_list[2] = 99 my_list.append(50) # [10, 20, 99, 40, 50]

print(my_list)
my_list.insert(1, 15) # [10, 15, 20, 99, 40, 50]
Output: [10, 20, 99, 40]

my_list.extend([60, 70]) # [..., 60, 70]


Modifying Lists: Removing Elements
Just as easily as you can add, you can remove elements from your lists. Choose the method that best suits whether you know the
value or the index.

By Value By Index
remove(): Deletes the first occurrence of a specified value. pop(): Removes and returns the element at a given index. If
Raises an error if the value is not found. no index is specified, it removes and returns the last item .

my_list.remove(99) my_list.pop()

my_list.pop(2)

By Index (Direct Delete) Clear All


del keyword: Deletes an element or slice of elements clear(): Empties the entire list, leaving it as [].
directly without returning them.
my_list.clear()
del my_list[0]
Searching and Counting Elements
Python lists offer convenient methods to check for the presence of elements and count their occurrences.

Find First Occurrence Count Occurrences

index(): Returns the index of the first occurrence of a specified count(): Returns the number of times a specified value appears
value. in the list.

Raises a ValueError if the item is not found.


print(my_list.count(20))

my_list = [10, 20, 20, 30]


Output: 2

Check for Presence


print(my_list.index(20))
Use the in keyword for a simple boolean check.
Output: 1

print(30 in my_list)

Output: True
Sorting and Reversing Lists
Organize your list elements in ascending or descending order, or simply reverse their current sequence.

In-place Sorting Reversing Order

sort(): Modifies the list in place (does not return a new list). reverse(): Reverses the order of elements in place .

my_list.sort(): Ascending order (default).


letters = ['c', 'a', 'b']
my_list.sort(reverse=True): Descending order.

nums = [3, 1, 4, 1, 5] letters.reverse() # ['b', 'a', 'c']

Sorted Copy
nums.sort() # [1, 1, 3, 4, 5]
sorted() (built-in function): Returns a new sorted list , leaving
the original unchanged.

original = [9, 2, 7]

new_sorted = sorted(original) # [2, 7, 9]


List Arithmetic & Built-in Functions
Lists support intuitive arithmetic operations and benefit from several powerful built-in Python functions.

Concatenation Useful Built-in Functions

Use the + operator to combine two or more lists. This creates a len(): Returns the number of items in a list.
new list. max(): Returns the largest item in a list.

min(): Returns the smallest item in a list.


a = [1, 2]
sum(): Returns the sum of all numeric items in a list.

b = [3, 4] my_list = [5, 10, 15]

print(a + b) # [1, 2, 3, 4] print(len(my_list)) # 3

Repetition
print(max(my_list)) # 15
Use the * operator with an integer to repeat a list's elements.

print(sum(my_list)) # 30
print(a * 2) # [1, 2, 1, 2]
Functions in python
Built1in List Methods (modify the original list in-place)

Method Purpose Syntax Example Result

append(x) Add element x at the lst.append(7) [1, 2] ³ [1, 2, 7] [1, 2, 7]


end

clear() Remove all elements lst.clear() [1, 2, 3] ³ [] []

copy() Return shallow copy lst.copy() b = a.copy() b == a but different id

count(x) Count occurrences lst.count("hi") ['hi', 'a', 'hi'] ³ 2 2


of x

extend(iter) Add elements from lst.extend([4,5]) [1,2] ³ [1,2,4,5] [1,2,4,5]


iterable

index(x) First index of element lst.index(3) [1,3,3] ³ 1 1


x

insert(i, x) Insert element x at lst.insert(1,"a") ["x"] ³ ["x","a"] ["x","a"]


position i

pop([i]) Remove and return lst.pop() [1,2,3].pop() ³ 3 and 3 and [1,2]


item at i (i defaults to [1,2]
31)

remove(x) Delete first lst.remove("a") ["a","b","a"].remove(" ["b","a"]


occurrence of x a") ³ ["b","a"]

reverse() Reverse order of lst.reverse() [1,2,3] ³ [3,2,1] [3,2,1]


elements

sort() Sort items in lst.sort() [3,1,2] ³ [1,2,3] [1,2,3] or [3,2,1] if


ascending order reverse=True
Functions in python
Built-in Functions Useful with Lists

Function Purpose Syntax Example Output

len(lst) Length of the list len([3,4,5]) 3

max(lst) Maximum element max(["b","a"]) "b"


(numeric or
lexicographic)

min(lst) Minimum element min([3,1]) 1

sum(lst) Sum of numeric sum([1,2,3]) 6


elements

sorted(lst) Return a sorted copy sorted([3,1,2]) [1,2,3]


of lst

any(lst) True if any element is any([0,0,5]) True


truthy

all(lst) True if all elements all([1,2,0]) FalseF


are truthy
Functions with Programs
1. Create and show a list
colors = ["red", "blue", "green"]

print("Original:", colors) # ['red', 'blue', 'green']

2. Append & Extend


colors.append("yellow")

colors.extend(["pink", "orange"])

print("After append/extend:", colors)

3. Insert, Remove, Pop


colors.insert(1, "black") # insert at index 1

print("Insert black:", colors)

colors.remove("green")

x = colors.pop(3) # remove and capture index 3

print("Popped element:", x)

print("After remove/pop:", colors)

4. Count, Index
colors.append("blue")

print("Count of blue:", colors.count("blue"))

print("Index of orange:", colors.index("orange"))

5. Sort & Reverse


colors.sort()

print("Sorted:", colors)

colors.reverse()

print("Reversed:", colors)

6. Copy & Clear


backup = colors.copy()

colors.clear()

print("Cleared original:", colors)

print("Backup copy:", backup)

7. Built-in functions
print("Length:", len(backup))

print("Max:", max(backup))

print("Min:", min(backup))

Numeric example:
nums = [10, 5, 30]

print("Sum:", sum(nums))

print("Sorted without changing original:", nums, sorted(nums))

print("Reversed view:", list(reversed(backup)))

You might also like