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

Python Lists: Creation and Operations

The document provides an introduction to Python lists, detailing their characteristics, creation methods, and various operations such as adding, deleting, and accessing elements. It explains list comprehensions, slicing, and the use of built-in functions for list manipulation. Additionally, it includes practical tasks for applying list concepts in real-world scenarios.

Uploaded by

Danish
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 views50 pages

Python Lists: Creation and Operations

The document provides an introduction to Python lists, detailing their characteristics, creation methods, and various operations such as adding, deleting, and accessing elements. It explains list comprehensions, slicing, and the use of built-in functions for list manipulation. Additionally, it includes practical tasks for applying list concepts in real-world scenarios.

Uploaded by

Danish
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

Introduction to python

[List]
Lists (What is List)
 The list class is a fundamental built-in data type in
Python.
 Lists are used to store multiple items in a single
variable.
Python’s list is a flexible, versatile, powerful, and
popular built-in data type.
It allows you to create variable-length and
mutable sequences of objects.
In a list, you can store objects of any type. You
can also mix objects of different types within the
same list, although list elements often share the
same type.
Lists (What is List)
Some of the characteristics of list objects include:
Ordered: They contain elements or items that
are sequentially arranged according to their
specific insertion order.
Zero-based: They allow you to access their
elements by indices that start from zero.
Mutable: They support in-place mutations or
changes to their contained elements.
Heterogeneous: They can store objects of
different types.
Lists (What is List)
Growable and dynamic: They can grow or shrink
dynamically, which means that they support the
insertion, and removal of elements.
Iterable: They support iteration, so you can
traverse them using a loop or comprehension
while you perform operations on each of their
elements.
Nestable: They can contain other lists, so you
can have lists of lists.
Lists (What is List)
Sliceable: They support slicing operations,
meaning that you can extract a series of
elements from them.
Combinable: They support concatenation
operations, so you can combine two or more
lists using the concatenation operators.
Copyable: They allow you to make copies of
their content using various techniques.
Lists (How to create List)
Python Lists are just like dynamically sized arrays,
declared in other languages (vector in C++ and
ArrayList in Java). In simple language, a list is a
collection of things, enclosed in [ ] and separated
by commas.
There are several ways to create a new list
The simplest is List literals: to enclose the
elements in square brackets (“[" and "]”)
The list() constructor
A list comprehension
Lists (Creating Lists Through Literals)
 List literals are probably the most popular way to create a
list object in Python. They consist of a pair of square brackets
enclosing a comma-separated series of objects.

Here’s the general syntax of a list literal: This syntax creates a list
of n items by listing the items in an enclosing pair of square brackets.
[item_0, item_1, ..., item_n]

 Examples:
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
['spam', 2.0, 5, [10, 20]]
Accessing Items/element in a List:
We can access individual element from a list using the element’s
associated index. Each item in a list has an index that specifies
its position in the list. Indices are integer numbers that start at
0 and go up to the number of element in the list -1.

 Example:
Comparison between (list of lists, list of tuples, list
of dictionaries)
Getting the size of Python list:
Python len() is used to get the length of the list.
Taking Input of a Python List
 To input a list of strings in Python, you can use
the input() function along with the split() method.
Taking Input of a Python List
 To input a list of numbers in Python, you can use
the input() function along with the split() method and then
convert each element to an integer.
Taking Input of a Python List
 If the user enters a mix of numbers and other characters,
you can filter out the non-numeric characters to ensure
your list contains only numbers.
Taking Input of a Python List
 To handle floating-point numbers in Python, you can use
the float() function to convert strings or integers to
floating-point numbers. Here’s an example of how to
input a list of floating-point numbers.
Traversing Lists
To traverse a list, you’ll need a loop that goes over each
element from the start to the end of the list. Python
provides several constructs that allow you to do this. The
most popular are for loops and list comprehension.
Retrieving Multiple Items From a List: Slicing
 in Python is a powerful feature that allows you to access
a subset of elements from sequences like lists, tuples,
and strings.
list_object[start : stop : step]

 The [start:stop:step] part of this construct is known as


the slicing operator. Its syntax consists of a pair of square
brackets and three optional indices, start, stop,
and step. The second colon is optional. You typically use
it only in those cases where you need a step value
different from 1.
Retrieving Multiple Items From a List: Slicing
Retrieving Multiple Items From a List: Slicing
Retrieving Multiple Items From a List: Slicing
Adding Elements to a List
 Lists are mutable, you can change their length by
adding or removing elements. So, lists are also variable-
length containers.
 Adding new items to a list or removing unneeded ones
are everyday tasks.
 Python provides different efficient ways to perform these
actions.
 Append(): adds a new element to the end of a list.
Extend(): takes a list as an argument and appends all
of the elements.
Insert(): adds a new element in a given position.
Adding Elements to a List : Append()
Adding Elements to a List : extend()
Adding Elements to a List : using ‘+’
Adding Elements to a List : insert()
Deleting Elements from a List
 Lists are mutable, you can change their length by
adding or removing elements. So, lists are also variable-
length containers.
 Python also allows you to remove one or more items
from an existing list.
 Python provides different efficient ways to perform these
actions.
 pop([index]):Removes the item at index and returns it back to
the caller. If you don’t provide a target index, then removes and
returns the last item in the list.
 remove(item): Removes the first occurrence of item from the list.
It raises a valueError if there’s no such item.
 del(): delete an element from a given position.
Deleting Elements from a List: pop()
Deleting Elements from a List: remove()
Deleting Elements from a List: del()
List operations
 Lists support other interesting operations like:

 Concatenation: Concatenation consists of joining two


things together. In this case, you’d like to
concatenate two lists, which you can do using the
plus operator (+).

Repetition: Repetition consists of cloning the content


of a given list a specific number of times. You can
achieve this with the repetition operator (*)
List operations
 Concatenation:

 Repetition:
Reversing and Sorting Lists
 Reversing and sorting lists of values are common tasks in
programming.
 We have built in methods .reverse() and .sort(), which
reverse and sort the target list in place

Reversing a List: reversed() and .reverse()

Sorting a List: sorted() and .sort()


Reversing and Sorting Lists
 Reversing a List: reversed()
 The built-in reversed() function takes a sequence as an argument
and returns an iterator that yields the values of that sequence in
reverse order.
 Reversed() is good when you want to iterate over a list in reverse
order without altering the original list
Reversing and Sorting Lists

 Reversing a List: .reverse()


The .reverse() method reverses a list in place. This means
that if you call .reverse() on an existing list, then the
changes will reflect in the underlying list.
Reversing and Sorting Lists
 Sorting a List: sorted()
When you need to sort a list of values without altering the original list,
you can use the built-in sorted() function. This function takes an
iterable of values and returns a list of sorted values
Reversing and Sorting Lists
 Sorting a List: sorted()
Python sorts strings character by character using each
character’s Unicode.
Reversing and Sorting Lists
 Sorting a List: .sort()
If you need to sort a list in place instead of getting a new list of sorted
data, then you can use the .sort() method.
Lists and functions
nums = [3, 41, 12, 9, 74, 15]
>>> print(len(nums))
6
>>> print(max(nums))
74
>>> print(min(nums))
3
>>> print(sum(nums))
154
>>> print(sum(nums)/len(nums))
25
Lists and strings

A string is a sequence of characters and a list is


a sequence of values, but a list of characters is
not the same as a string.
Lists and strings

A string is a sequence of characters and a list is


a sequence of values, but a list of characters is
not the same as a string.
Lists (Creating list() Constructor)
 Another tool that allows you to create list objects is the
class constructor, list(). You can call this constructor with
any iterable object, including other lists, tuples, sets, dictionaries
and their components, strings, and many others.

 Here’s the general syntax of a list

list( [ iterable ] )

 To create a list, you need to call list() as you’d call any class
constructor or function.
Lists (Creating list() Constructor)
Lists (Creating Lists With List Comprehensions)
 List comprehensions are one of the most distinctive
features of Python.
 List comprehensions allow you to quickly create and
transform lists using a syntax that mimics a for loop but in
a single line of code.
 The core syntax of list comprehensions

[expression(item) for item in iterable]

Every list comprehension needs at least three components:


 expression() is a Python expression that returns a concrete value,
and most of the time, that value depends on item. Note that it
doesn’t have to be a function.
 item is the current object from iterable.
 iterable can be any Python iterable object, such as
a list, tuple, set, string, or generator.
Lists (Creating Lists With List Comprehensions)
Task 01
A teacher records students’ marks in different subjects.
Task Requirements:
• Store students’ marks using a list of dictionaries.
• Write a user-defined function to calculate each student’s average.
• Use a loop to process all students.
• Use conditional statements to assign grades (A, B, C, Fail).
• Use built-in functions like sum() and len().
Output
Input
Task: 02
You are working as a climate data analyst. Write a Python program to monitor and
analyze daily temperature readings for a city. Store the temperature readings for
multiple days using a list of lists, where each inner list contains hourly temperature
readings for one day.
Your program should:
Use append() to add each new day's temperature readings into the main list as
input from user.
Use a loop to process all days and display:
•highest temperature of the day (using max())
•lowest temperature of the day (using min())
For any day where the maximum temperature exceeds 40°C, print "Heatwave
alert".
Display clear output showing the analysis for each day.
Output
Input

You might also like