SlideShare a Scribd company logo
Lists
List
• The Python lists are containers that are used to store a list of
values of any type. Unlike other variables, Python lists are
mutable, i.e., you can change the elements of a list in place;
Python will not create a fresh list when you make changes to
an element of a list. List is a type of sequence like strings and
tuples but it differs from them in the way that lists are mutable
but strings and tuples are immutable
Properties of list
• 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.
• Growable and dynamic: They can grow or shrink dynamically, which means that they support the addition, insertion, and
removal of elements.
• Nestable: They can contain other lists, so you can have lists of lists.
• Iterable: They support iteration, so you can traverse them using a loop or comprehension while you perform operations on each
of their elements.
• 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.
Creating and Accessing Lists
• A list is a standard data type of Python that can store a sequence of values belonging to
any type. The Lists are depicted through square brackets, e.g., following are some lists
in Python:
• [] # list with no member, empty list
• [1, 2, 3] # list of integers
• [1, 2.5, 3.7, 9] # list of numbers (integers and floating point)
• ['a', 'b', 'c'] # list of characters
• ['a', 1, 'b', 3.5, 'zero'] # list of mixed value types
• ['One', 'Two', 'Three'] # list of strings
Creating Lists
• To create a list, put a number of expressions in square brackets. That is,
use square brackets to indicate the start and end of the list, and separate
the items by commas. For example:
• [2, 4, 6]
• ['abc', 'def’]
• [1, 2.0, 3, 4.0]
• []
The empty list:
The empty list is []. It is the list equivalent of 0
or "" and like them it also has truth value as
false. You can also create an empty list as : L
= list()
Long lists
If a list contains many elements, then enter
such long lists, you can split it across several
lines, like below:
sqrs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100,
121, 144, 169,196, 225, 256, 289, 324, 361,
400, 441, 484, 529, 576, 625]
Nested lists
A list can have an element in it, which itself is
a list. Such a list is called nested list. e.g.,
L1 = [3, 4, [5, 6], 7]L1 is a nested list with four
elements: 3, 4, [5, 6] and 7. L1[2] element is a
list [5, 6].Length of L1 is 4 as it counts [5, 6] as
one element. Also, as L1[2] is a list (i.e., [5, 6]),
which means L1[2][0] will give 5 and L1[2][1]
will give 6
Creating Lists from Existing
Sequences
You can also use the built-in list type object to
create lists from sequences as per the syntax
given below:
L = list(<sequence>)
• where <sequence> can be any kind of sequence object including
strings, tuples, and lists. Python creates the individual elements of the
list from the individual elements of passed sequence. If you pass in
another list, the list function makes a copy.
Consider following examples :
>>> l1 = list('hello’)
>>> l1['h', 'e', 'l', 'l', 'o’]
>>> t = ('h', 'e', 'l', 'l', 'o’)
>>> l2 = list(t)
>>> l2['h', 'e', 'l', 'l', 'o’]
• L1 is created from another sequence - a string 'hello'.It generated individual
elements from the individual letters of the string
• L2 is created from another sequence- a tuple.It generated individual elements
from the individual elements of the passed tuple t.
Accessing Items in a List: Indexing
You can access individual items from a list using the item’s associated index. What’s an
item’s 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 items in the list minus 1.
To access a list item through its index, you
use the following syntax:
list_object[index]
This construct is known as an indexing operation, and the [index] part is known as the
indexing operator. It consists of a pair of square brackets enclosing the desired or target
index.
>>> languages = ["Python", "Java", "JavaScript", "C++", "Go", "Rust"]
>>> languages[0]
'Python'
>>> languages[1]
'Java'
>>> languages[2]
'JavaScript'
>>> languages[3]
'C++'
>>> languages[4]
'Go'
>>> languages[5]
'Rust'
>>> languages[-1]
'Rust'
>>> languages[-2]
'Go'
>>> languages[-3]
'C++'
>>> languages[-4]
'JavaScript'
>>> languages[-5]
'Java'
>>> languages[-6]
'Python'
Slicing
• You can access the list elements just like you access a string's elements e.g.,
List[i] will give you the element at ith index of the list ; List[a:b] will give you
elements between indexes a to b-1 and so on. The syntax is as follows.
• 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.
start specifies the index at which you want to start the
slicing. The resulting slice includes the item at this
index.
stop specifies the index at which you want the slicing
to stop extracting items. The resulting slice doesn’t
include the item at this index.
step provides an integer value representing how
many items the slicing will skip on each step. The
resulting slice won’t include the skipped items.
>>> letters = ["A", "a", "B", "b", "C", "c", "D", "d"]
>>> upper_letters = letters[0::2] # Or [::2]
>>> upper_letters
['A', 'B', 'C', 'D']
>>> lower_letters = letters[1::2]
>>> lower_letters
['a', 'b', 'c', 'd']
>>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> first_three = digits[:3]
>>> first_three
[0, 1, 2]
>>> middle_four = digits[3:7]
>>> middle_four
[3, 4, 5, 6]
>>> last_three = digits[-3:]
>>> last_three
[7, 8, 9]
>>> every_other = digits[::2]
>>> every_other
[0, 2, 4, 6, 8]
>>> every_three = digits[::3]
>>> every_three
[0, 3, 6, 9]
Traversing a List
• Traversal of a sequence means accessing and processing each element of
it. Thus traversing a list also means the same and same is the tool for it, i.e.,
the Python loops. That is why sometimes we call a traversal as looping over
a sequence. For example
L = ['P', 'y', 't', 'h', 'o', 'n']
for a in L:
print(a)
Comparing Lists
• You can compare two lists using standard comparison operators of
Python, i.e., <, >, <=, >=, ==, !=, etc.
• Python internally compares individual elements of lists (and tuples) in
lexicographical order. This means that to compare equal, each
corresponding element must compare equal and the two sequences
must be of the same type i.e., having comparable types of values.
Consider following examples :
>>> L1, L2 = [1, 2, 3], [1, 2, 3]
>>> L3 = [1, [2, 3]]
>>> L1 == L2
True
>>> L1 == L3
False
For comparison operators >, <, >=, <=, the corresponding elements of two lists must be of
comparable types, otherwise Python will give error.
Consider the following, considering the above two lists:
>>> L1 < L2
False
>>> L1 < L3
Traceback (most recent call last):
File "<ipython-input-180-84fdf598c3f1>", line 1, in <module>
L1 < L3
TypeError: '<' not supported between instances of 'int' and 'list’
• For first comparison, Python did not give any error as both lists have values of same type.
• For second comparison, as the values are not of comparable types, Python raised error
• Python raised error above because the corresponding second elements of lists i.e., L1[1] and
L3[1] are not of comparable types. L1[1] is integer (2) and L3[1] is a list [2, 3] and list and numbers
are not comparable types in Python
• Python gives the final result of non-equality comparisons
as soon as it gets a result in terms of True/False from
corresponding elements' comparison. If corresponding
elements are equal, it goes on to the next element, and so
on, until it finds elements that differ. Subsequent
elements are not considered
Comparison Result Reason
[1, 2, 8, 9] < [9, 1] True
Gets the result with the
comparison of corresponding
first elements of two lists. 1 <
9 is True
[1, 2, 8, 9] < [1, 2, 9, 1] True
Gets the result with the
comparison of corresponding
third elements of two lists. 8 <
9 is True
[1, 2, 8, 9] < [1, 2, 9, 10] True
Gets the result with the
comparison of corresponding
third elements of two lists. 8 <
9 is True
[1, 2, 8, 9] < [1, 2, 8, 4] False
Gets the result with the
comparison of corresponding
fourth elements of two lists. 9
< 4 is False
>>> a = [2, 3]
>>> b = [2, 3]
>>> c = ['2', '3']
>>> d = [2.0, 3.0]
>>> e = [2, 3, 4]
>>> a == b
True
>>> a == c
False
>>> a > b
False
>>> d > a
False
>>> d == a
True
>>> a < e
True
For two lists to be
equal, they must
have same number
of elements and
matching values
• Membership operators
Both 'in' and 'not in' operators work on Lists just like they work for other
sequences. That is, in tells if an element is present in the list or not, and not
in does the opposite.
• Concatenation and replication operators + and *
The + operator adds one list to the end of another. The * operator repeats a
list.
insert()
• The insert() method adds an element to a specific index in the list. It
takes two arguments: the index where the element will be inserted and
the value to be inserted. For example:
letters = ['a', 'b', 'c', 'd']
letters.insert(2, 'e')
print(letters)
# Output: ['a', 'b', 'e', 'c', 'd']
remove()
• The remove() method removes the first occurrence of a specified
element in the list. It takes a single argument, which is the element to be
removed. For example:
numbers = [1, 2, 3, 4, 5]
numbers.remove(3)
print(numbers)
# Output: [1, 2, 4, 5]
pop()
• The pop() method removes the element at a specified index in the list and returns it. If
no index is specified, it removes and returns the last element in the list. For example:
letters = ['a', 'b', 'c', 'd']
x = letters.pop(1)
print(x)
# Output: 'b'
print(letters)
# Output: ['a', 'c', 'd']
sort()
• The sort() method sorts the elements in the list in ascending order by default. It can also sort the list in
descending order by specifying the reverse parameter as True. For example:
numbers = [5, 2, 1, 3, 4]
numbers.sort()
print(numbers)
# Output: [1, 2, 3, 4, 5]
numbers.sort(reverse=True)
print(numbers)
# Output: [5, 4, 3, 2, 1]
count()
• The count() method returns the number of times a specified element
appears in the list. It takes a single argument, which is the element to be
counted. For example:
fruits = ['apple', 'banana', 'cherry', 'banana']
x = fruits.count('banana')
print(x)
index()
• The index() method returns the index of the first occurrence of a
specified element in the list. It takes a single argument, which is the
element to be searched. For example:
numbers = [1, 2, 3, 4, 5]
x = numbers.index(3)
print(x)
# Output: 2
append()
• This method is used to add an item to the end of a list. For example,
numbers = [1, 2, 3]
numbers.append(4)
will add the number 4 to the end of the list. So, numbers will be
[1, 2, 3, 4].
extend()
• This method is used to add multiple items to the end of a list. The argument passed to
the method should be an iterable (e.g. a list or a tuple). For example,
numbers = [1, 2, 3]
numbers.extend([4, 5, 6])
will add the numbers 4, 5, and 6 to the end of the list. This is also possible to do with
numbers += [4, 5, 6].
In both cases, the list numbers will have [1, 2, 3, 4, 5, 6]

More Related Content

PPTX
Python data type
Jaya Kumari
 
PPTX
11 Introduction to lists.pptx
ssuser8e50d8
 
PDF
List , tuples, dictionaries and regular expressions in python
channa basava
 
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
PDF
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
PDF
Python Basics it will teach you about data types
NimitSinghal2
 
PPTX
Module 2 - Lists, Tuples, Files.pptx
GaneshRaghu4
 
PPTX
Presentation python programming vtu 6th sem
ssuser8f6b1d1
 
Python data type
Jaya Kumari
 
11 Introduction to lists.pptx
ssuser8e50d8
 
List , tuples, dictionaries and regular expressions in python
channa basava
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
Python Basics it will teach you about data types
NimitSinghal2
 
Module 2 - Lists, Tuples, Files.pptx
GaneshRaghu4
 
Presentation python programming vtu 6th sem
ssuser8f6b1d1
 

Similar to Lists and its functions in python for beginners (20)

PPTX
Python for Beginners(v3)
Panimalar Engineering College
 
PPTX
Python-List.pptx
AnitaDevi158873
 
PPTX
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
Out Cast
 
PPTX
Python Programming for BCS Degree UNIT -4.pptx
magerebenard
 
PDF
List in Python Using Back Developers in Using More Use.
SravaniSravani53
 
PDF
Python revision tour II
Mr. Vikram Singh Slathia
 
PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Guru Nanak Technical Institutions
 
PPTX
Python Lecture 8
Inzamam Baig
 
PPTX
Lists on the pyhton to learn the children more easily on easy codes.pptx
cjrfailure
 
PPTX
Brief Explanation On List and Dictionaries of Python
nikhita4775
 
PDF
Notes3
hccit
 
PPTX
2. Values and Data types in Python.pptx
deivanayagamramachan
 
PPTX
IPP-M2-C1-Lists-Data Types.pptx for project management
tahir843188
 
PPTX
02 Python Data Structure.pptx
ssuser88c564
 
PPTX
updated_list.pptx
Koteswari Kasireddy
 
PPTX
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
PPTX
Python
reshmaravichandran
 
PDF
Python lecture 04
Tanwir Zaman
 
PPT
Data types usually used in python for coding
PriyankaRajaboina
 
Python for Beginners(v3)
Panimalar Engineering College
 
Python-List.pptx
AnitaDevi158873
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
Out Cast
 
Python Programming for BCS Degree UNIT -4.pptx
magerebenard
 
List in Python Using Back Developers in Using More Use.
SravaniSravani53
 
Python revision tour II
Mr. Vikram Singh Slathia
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Guru Nanak Technical Institutions
 
Python Lecture 8
Inzamam Baig
 
Lists on the pyhton to learn the children more easily on easy codes.pptx
cjrfailure
 
Brief Explanation On List and Dictionaries of Python
nikhita4775
 
Notes3
hccit
 
2. Values and Data types in Python.pptx
deivanayagamramachan
 
IPP-M2-C1-Lists-Data Types.pptx for project management
tahir843188
 
02 Python Data Structure.pptx
ssuser88c564
 
updated_list.pptx
Koteswari Kasireddy
 
fundamental of python --- vivek singh shekawat
shekhawatasshp
 
Python lecture 04
Tanwir Zaman
 
Data types usually used in python for coding
PriyankaRajaboina
 
Ad

More from Mohammad Usman (18)

PPTX
Transformation in Education from past to current
Mohammad Usman
 
PDF
AI for Data Analysis and Visualization.pdf
Mohammad Usman
 
PPTX
Functions in Python and its types for beginners
Mohammad Usman
 
PPTX
Modules and its usage in python for beginners
Mohammad Usman
 
PPTX
Credit Card Fraud Detection Using AI.pptx
Mohammad Usman
 
PPTX
Exploring Search Engines and their usage online
Mohammad Usman
 
PPTX
Web Technologies Types available on the internet
Mohammad Usman
 
PPTX
AI open tools for Research.pptx
Mohammad Usman
 
PPTX
Open AI Tools for Data Analytics
Mohammad Usman
 
PDF
Data structures and algorithms
Mohammad Usman
 
PDF
Object oriented programming with c++
Mohammad Usman
 
PPTX
Dynamic memory allocation
Mohammad Usman
 
DOCX
Career Guide
Mohammad Usman
 
DOCX
C areer banner
Mohammad Usman
 
DOCX
Career counselling banner
Mohammad Usman
 
DOCX
Career ccc
Mohammad Usman
 
DOCX
Career ccc hindi
Mohammad Usman
 
PPT
Literacy for or_against_the_poor_seminar
Mohammad Usman
 
Transformation in Education from past to current
Mohammad Usman
 
AI for Data Analysis and Visualization.pdf
Mohammad Usman
 
Functions in Python and its types for beginners
Mohammad Usman
 
Modules and its usage in python for beginners
Mohammad Usman
 
Credit Card Fraud Detection Using AI.pptx
Mohammad Usman
 
Exploring Search Engines and their usage online
Mohammad Usman
 
Web Technologies Types available on the internet
Mohammad Usman
 
AI open tools for Research.pptx
Mohammad Usman
 
Open AI Tools for Data Analytics
Mohammad Usman
 
Data structures and algorithms
Mohammad Usman
 
Object oriented programming with c++
Mohammad Usman
 
Dynamic memory allocation
Mohammad Usman
 
Career Guide
Mohammad Usman
 
C areer banner
Mohammad Usman
 
Career counselling banner
Mohammad Usman
 
Career ccc
Mohammad Usman
 
Career ccc hindi
Mohammad Usman
 
Literacy for or_against_the_poor_seminar
Mohammad Usman
 
Ad

Recently uploaded (20)

PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PDF
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PDF
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Understanding operators in c language.pptx
auteharshil95
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 

Lists and its functions in python for beginners

  • 2. List • The Python lists are containers that are used to store a list of values of any type. Unlike other variables, Python lists are mutable, i.e., you can change the elements of a list in place; Python will not create a fresh list when you make changes to an element of a list. List is a type of sequence like strings and tuples but it differs from them in the way that lists are mutable but strings and tuples are immutable
  • 3. Properties of list • 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. • Growable and dynamic: They can grow or shrink dynamically, which means that they support the addition, insertion, and removal of elements. • Nestable: They can contain other lists, so you can have lists of lists. • Iterable: They support iteration, so you can traverse them using a loop or comprehension while you perform operations on each of their elements. • 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.
  • 4. Creating and Accessing Lists • A list is a standard data type of Python that can store a sequence of values belonging to any type. The Lists are depicted through square brackets, e.g., following are some lists in Python: • [] # list with no member, empty list • [1, 2, 3] # list of integers • [1, 2.5, 3.7, 9] # list of numbers (integers and floating point) • ['a', 'b', 'c'] # list of characters • ['a', 1, 'b', 3.5, 'zero'] # list of mixed value types • ['One', 'Two', 'Three'] # list of strings
  • 5. Creating Lists • To create a list, put a number of expressions in square brackets. That is, use square brackets to indicate the start and end of the list, and separate the items by commas. For example: • [2, 4, 6] • ['abc', 'def’] • [1, 2.0, 3, 4.0] • []
  • 6. The empty list: The empty list is []. It is the list equivalent of 0 or "" and like them it also has truth value as false. You can also create an empty list as : L = list() Long lists If a list contains many elements, then enter such long lists, you can split it across several lines, like below: sqrs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169,196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625]
  • 7. Nested lists A list can have an element in it, which itself is a list. Such a list is called nested list. e.g., L1 = [3, 4, [5, 6], 7]L1 is a nested list with four elements: 3, 4, [5, 6] and 7. L1[2] element is a list [5, 6].Length of L1 is 4 as it counts [5, 6] as one element. Also, as L1[2] is a list (i.e., [5, 6]), which means L1[2][0] will give 5 and L1[2][1] will give 6 Creating Lists from Existing Sequences You can also use the built-in list type object to create lists from sequences as per the syntax given below: L = list(<sequence>)
  • 8. • where <sequence> can be any kind of sequence object including strings, tuples, and lists. Python creates the individual elements of the list from the individual elements of passed sequence. If you pass in another list, the list function makes a copy. Consider following examples : >>> l1 = list('hello’) >>> l1['h', 'e', 'l', 'l', 'o’] >>> t = ('h', 'e', 'l', 'l', 'o’) >>> l2 = list(t) >>> l2['h', 'e', 'l', 'l', 'o’] • L1 is created from another sequence - a string 'hello'.It generated individual elements from the individual letters of the string • L2 is created from another sequence- a tuple.It generated individual elements from the individual elements of the passed tuple t.
  • 9. Accessing Items in a List: Indexing You can access individual items from a list using the item’s associated index. What’s an item’s 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 items in the list minus 1. To access a list item through its index, you use the following syntax: list_object[index] This construct is known as an indexing operation, and the [index] part is known as the indexing operator. It consists of a pair of square brackets enclosing the desired or target index.
  • 10. >>> languages = ["Python", "Java", "JavaScript", "C++", "Go", "Rust"] >>> languages[0] 'Python' >>> languages[1] 'Java' >>> languages[2] 'JavaScript' >>> languages[3] 'C++' >>> languages[4] 'Go' >>> languages[5] 'Rust'
  • 11. >>> languages[-1] 'Rust' >>> languages[-2] 'Go' >>> languages[-3] 'C++' >>> languages[-4] 'JavaScript' >>> languages[-5] 'Java' >>> languages[-6] 'Python'
  • 12. Slicing • You can access the list elements just like you access a string's elements e.g., List[i] will give you the element at ith index of the list ; List[a:b] will give you elements between indexes a to b-1 and so on. The syntax is as follows. • 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.
  • 13. start specifies the index at which you want to start the slicing. The resulting slice includes the item at this index. stop specifies the index at which you want the slicing to stop extracting items. The resulting slice doesn’t include the item at this index. step provides an integer value representing how many items the slicing will skip on each step. The resulting slice won’t include the skipped items.
  • 14. >>> letters = ["A", "a", "B", "b", "C", "c", "D", "d"] >>> upper_letters = letters[0::2] # Or [::2] >>> upper_letters ['A', 'B', 'C', 'D'] >>> lower_letters = letters[1::2] >>> lower_letters ['a', 'b', 'c', 'd']
  • 15. >>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> first_three = digits[:3] >>> first_three [0, 1, 2] >>> middle_four = digits[3:7] >>> middle_four [3, 4, 5, 6] >>> last_three = digits[-3:] >>> last_three [7, 8, 9] >>> every_other = digits[::2] >>> every_other [0, 2, 4, 6, 8] >>> every_three = digits[::3] >>> every_three [0, 3, 6, 9]
  • 16. Traversing a List • Traversal of a sequence means accessing and processing each element of it. Thus traversing a list also means the same and same is the tool for it, i.e., the Python loops. That is why sometimes we call a traversal as looping over a sequence. For example L = ['P', 'y', 't', 'h', 'o', 'n'] for a in L: print(a)
  • 17. Comparing Lists • You can compare two lists using standard comparison operators of Python, i.e., <, >, <=, >=, ==, !=, etc. • Python internally compares individual elements of lists (and tuples) in lexicographical order. This means that to compare equal, each corresponding element must compare equal and the two sequences must be of the same type i.e., having comparable types of values.
  • 18. Consider following examples : >>> L1, L2 = [1, 2, 3], [1, 2, 3] >>> L3 = [1, [2, 3]] >>> L1 == L2 True >>> L1 == L3 False
  • 19. For comparison operators >, <, >=, <=, the corresponding elements of two lists must be of comparable types, otherwise Python will give error. Consider the following, considering the above two lists: >>> L1 < L2 False >>> L1 < L3 Traceback (most recent call last): File "<ipython-input-180-84fdf598c3f1>", line 1, in <module> L1 < L3 TypeError: '<' not supported between instances of 'int' and 'list’ • For first comparison, Python did not give any error as both lists have values of same type. • For second comparison, as the values are not of comparable types, Python raised error • Python raised error above because the corresponding second elements of lists i.e., L1[1] and L3[1] are not of comparable types. L1[1] is integer (2) and L3[1] is a list [2, 3] and list and numbers are not comparable types in Python
  • 20. • Python gives the final result of non-equality comparisons as soon as it gets a result in terms of True/False from corresponding elements' comparison. If corresponding elements are equal, it goes on to the next element, and so on, until it finds elements that differ. Subsequent elements are not considered
  • 21. Comparison Result Reason [1, 2, 8, 9] < [9, 1] True Gets the result with the comparison of corresponding first elements of two lists. 1 < 9 is True [1, 2, 8, 9] < [1, 2, 9, 1] True Gets the result with the comparison of corresponding third elements of two lists. 8 < 9 is True [1, 2, 8, 9] < [1, 2, 9, 10] True Gets the result with the comparison of corresponding third elements of two lists. 8 < 9 is True [1, 2, 8, 9] < [1, 2, 8, 4] False Gets the result with the comparison of corresponding fourth elements of two lists. 9 < 4 is False
  • 22. >>> a = [2, 3] >>> b = [2, 3] >>> c = ['2', '3'] >>> d = [2.0, 3.0] >>> e = [2, 3, 4] >>> a == b True >>> a == c False >>> a > b False >>> d > a False >>> d == a True >>> a < e True For two lists to be equal, they must have same number of elements and matching values
  • 23. • Membership operators Both 'in' and 'not in' operators work on Lists just like they work for other sequences. That is, in tells if an element is present in the list or not, and not in does the opposite. • Concatenation and replication operators + and * The + operator adds one list to the end of another. The * operator repeats a list.
  • 24. insert() • The insert() method adds an element to a specific index in the list. It takes two arguments: the index where the element will be inserted and the value to be inserted. For example: letters = ['a', 'b', 'c', 'd'] letters.insert(2, 'e') print(letters) # Output: ['a', 'b', 'e', 'c', 'd']
  • 25. remove() • The remove() method removes the first occurrence of a specified element in the list. It takes a single argument, which is the element to be removed. For example: numbers = [1, 2, 3, 4, 5] numbers.remove(3) print(numbers) # Output: [1, 2, 4, 5]
  • 26. pop() • The pop() method removes the element at a specified index in the list and returns it. If no index is specified, it removes and returns the last element in the list. For example: letters = ['a', 'b', 'c', 'd'] x = letters.pop(1) print(x) # Output: 'b' print(letters) # Output: ['a', 'c', 'd']
  • 27. sort() • The sort() method sorts the elements in the list in ascending order by default. It can also sort the list in descending order by specifying the reverse parameter as True. For example: numbers = [5, 2, 1, 3, 4] numbers.sort() print(numbers) # Output: [1, 2, 3, 4, 5] numbers.sort(reverse=True) print(numbers) # Output: [5, 4, 3, 2, 1]
  • 28. count() • The count() method returns the number of times a specified element appears in the list. It takes a single argument, which is the element to be counted. For example: fruits = ['apple', 'banana', 'cherry', 'banana'] x = fruits.count('banana') print(x)
  • 29. index() • The index() method returns the index of the first occurrence of a specified element in the list. It takes a single argument, which is the element to be searched. For example: numbers = [1, 2, 3, 4, 5] x = numbers.index(3) print(x) # Output: 2
  • 30. append() • This method is used to add an item to the end of a list. For example, numbers = [1, 2, 3] numbers.append(4) will add the number 4 to the end of the list. So, numbers will be [1, 2, 3, 4].
  • 31. extend() • This method is used to add multiple items to the end of a list. The argument passed to the method should be an iterable (e.g. a list or a tuple). For example, numbers = [1, 2, 3] numbers.extend([4, 5, 6]) will add the numbers 4, 5, and 6 to the end of the list. This is also possible to do with numbers += [4, 5, 6]. In both cases, the list numbers will have [1, 2, 3, 4, 5, 6]