0% found this document useful (0 votes)
16 views15 pages

Understanding Python Lists and Errors

The document provides a comprehensive overview of Python lists, covering their creation, properties, and various operations such as slicing, indexing, and modifying elements. It explains that lists are mutable data structures that can store multiple data types and includes examples of how to create and manipulate lists. Additionally, it highlights the use of methods like append, extend, and insert for adding elements, as well as techniques for accessing and deleting list items.
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)
16 views15 pages

Understanding Python Lists and Errors

The document provides a comprehensive overview of Python lists, covering their creation, properties, and various operations such as slicing, indexing, and modifying elements. It explains that lists are mutable data structures that can store multiple data types and includes examples of how to create and manipulate lists. Additionally, it highlights the use of methods like append, extend, and insert for adding elements, as well as techniques for accessing and deleting list items.
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

2/15/25, 7:40 PM 003_Python_List

Python List
In this class, we'll learn everything about Python lists, how they are created, slicing of a list,
adding or removing elements from them and so on.

Python offers a range of compound data types often referred to as sequences. List is one of
the most frequently used and very versatile data types used in Python.

What is List in Python?


Python list is a data structure which is used to store various types of [Link] Python, lists are
mutable i.e., Python will not create a new list if we modify an element of the list.

It works as a container that holds other objects in a given order. We can perform various
operations like insertion and deletion on list. A list can be composed by storing a sequence
of different type of values separated by commas.

Summary
Data types Type

String immutable

List mutable ✎

Creating Python List


In Python programming, a list is created by placing all the items (elements) inside square
brackets [] , separated by commas , . All the elements in list are stored in the index basis
with starting index 0.

It can have any number of items and they may be of different types (integer, float, string
etc.).

Syantax:

<list_name>=[value1,value2,value3,...,valuen]

In [1]: # Example:

# empty list, no item in the list


my_list = []
print(my_list) # ▶ ()
print(len(my_list)) # ▶ 0

# list of integers
my_list1 = [1, 2, 3]
print(my_list1) # ▶ [1, 2, 3]

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 1/15


2/15/25, 7:40 PM 003_Python_List
# list with mixed data types
my_list2 = [1, "Hello", 3.4]
print(my_list2) # ▶ [1, 'Hello', 3.4]

# nested list
my_list3 = ["mouse", [9, 3, 6], ['a']]
print(my_list3) # ▶ ["mouse", [9, 3, 6], ['a']]

my_list4=['foo','bar','baz','quz','quux','corge']
print(my_list4) # ▶ ['foo','bar','baz','quz','quux','corge']

my_list5=[1,2,3,4,4.5,'helloworld','X']
print(my_list5) # ▶ [1,2,3,4,4.5,'helloworld','X']

[]
0
[1, 2, 3]
[1, 'Hello', 3.4]
['mouse', [9, 3, 6], ['a']]
['foo', 'bar', 'baz', 'quz', 'quux', 'corge']
[1, 2, 3, 4, 4.5, 'helloworld', 'X']

Access elements from a list


There are various ways in which we can access the elements of a list.

List Index
We can use the index operator [] to access an item in a list. In Python, indices start at 0.
So, a list having 5 elements will have an index from 0 to 4.

Trying to access indexes other than these will raise an IndexError . The index must be an
integer. We can't use float or other types, this will result in TypeError .

Nested lists are accessed using nested indexing.

In [2]: # Example: List indexing

my_list = ['p', 'r', 'o', 'b', 'e']

print(my_list[0]) # ▶ p
print(my_list[2]) # ▶ o
print(my_list[4]) # ▶ e

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1]) # ▶ a
print(n_list[1][3]) # ▶ 5

print(my_list[4.0]) # ▶ TypeError: list indices must be integers or slices, not fl

p
o
e
a
5
localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 2/15
2/15/25, 7:40 PM 003_Python_List

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-0a4959e7a13b> in <module>
14 print(n_list[1][3]) # ▶ 5
15
---> 16 print(my_list[4.0]) # ▶ TypeError: list indices must be integers or slice
s, not float

TypeError: list indices must be integers or slices, not float

Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.

In [3]: # Example: Negative indexing in lists

# Python allows negative indexing for its sequences.


#The index of -1 refers to the last item, -2 to the second last item and so on.

my_list = ['p','r','o','b','e']

print(my_list[-1]) # ▶ e
print(my_list[-5]) # ▶ p

e
p

Note: If the index provided in the list slice is outside the list, then it raises an
IndexError exception.

How to slice lists in Python?


We can access a range of items in a list by using the slicing operator : (colon).

Syntax:

<list_name>[start : stop : step]

In [4]: # Example: List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','n','g']
# indes [ 0 1 2 3 4 5 6 7 8 9 ]
# index [-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ]

print(my_list[2:5]) # ▶ ['o', 'g', 'r'] ∵ elements 3rd to 4th


print(my_list[:-5]) # ▶ ['p', 'r', 'o', 'g', 'r'] ∵ elements beginning to 4th
print(my_list[5:]) # ▶ ['a', 'm', 'i', 'n', 'g'] ∵ elements 5th to end

# elements beginning to end


print(my_list[:]) # ▶ ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n','g')

['o', 'g', 'r']


['p', 'r', 'o', 'g', 'r']
['a', 'm', 'i', 'n', 'g']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n', 'g']

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 3/15


2/15/25, 7:40 PM 003_Python_List

Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need two indices that will slice that portion from
the list.

NOTE: Internal Memory Organization:

List do not store the elements directly at the index. In fact a reference is
stored at each index which subsequently refers to the object stored
somewhere in the memory. This is due to the fact that some objects may be
large enough than other objects and hence they are stored at some other
memory location.

In [5]: # Example:

list=['foo','bar','baz','quz','quux','corge']

print(list[2]) # ▶ baz
print(list[0:]) # ▶ ['foo', 'bar', 'baz', 'quz', 'quux', 'corge'] ∵ if we d
print(list[4:6]) # ▶ ['quux', 'corge']
print(list[-4:-1]) # ▶ ['baz', 'quz', 'quux'] ∵ it does not include the end in
print(list[1:5:2]) # ▶ ['bar', 'quz'] ∵ it does not include the end index
print(list[-1: :-1]) # ▶ ['corge', 'quux', 'quz', 'baz', 'bar', 'foo'] ∵ reverse
print(list[-1]) # ▶ corge ∵ last element
print(list[-2]) # ▶ quux ∵ second last element
print(len(list)-1) # ▶ 5 ∵ index of last element

does_exist = 'bar' in list


print(does_exist) # ▶ True

baz
['foo', 'bar', 'baz', 'quz', 'quux', 'corge']
['quux', 'corge']
['baz', 'quz', 'quux']
['bar', 'quz']
['corge', 'quux', 'quz', 'baz', 'bar', 'foo']
corge
quux
5
True

Python List Operations


Apart from creating and accessing elements from the list, Python allows us to perform
various other operations on the list. Some common operations are given below:

Add/Change List Elements


Lists are mutable, meaning their elements can be changed unlike string or tuple.

We can use the assignment operator ( = ) to change an item or a range of items.

In [6]: # Example: Correcting mistake values in a list

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 4/15


2/15/25, 7:40 PM 003_Python_List
odd = [2, 4, 6, 8]

odd[0] = 1 # ▶ [1, 4, 6, 8] ∵ update 1st element


print(odd)

odd[1:4] = [3, 5, 7] # ▶ [1, 3, 5, 7] ∵ update 2nd to 4th elements


print(odd)

[1, 4, 6, 8]
[1, 3, 5, 7]

In [7]: # Example:

data1=[5,10,15,20,25]
print(data1) # ▶ [5, 10, 15, 20, 25]

data1[2]="Multiple of 5" # we are modifying the 3rd element using its index [2]
print(data1) # ▶ [5, 10, 'Multiple of 5', 20, 25]

[5, 10, 15, 20, 25]


[5, 10, 'Multiple of 5', 20, 25]

We can add one item to a list using the append() method or add several items using
extend() method.

In [8]: # Example: Appending and Extending lists in Python

odd = [1, 3, 5]

[Link](7)
print(odd) # ▶ [1, 3, 5, 7]

[Link]([9, 11, 13])


print(odd) # ▶ [1, 3, 5, 7, 9, 11, 13]

[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]

In [9]: # Example:

list1=['a','b','c']
[Link](1.5)
[Link]('x')
[Link](['y','z']) # append list into list as single object
print(list1) # ▶ ['a', 'b', 'c', 1.5, 'x', ['y', 'z']]

['a', 'b', 'c', 1.5, 'x', ['y', 'z']]

We can also use + (concatenation) operator to combine two lists. This is also called
concatenation.

In [10]: # Example: Concatenating and repeating lists

odd = [1, 3, 5]
print(odd + [9, 7, 5]) # ▶ [1, 3, 5, 9, 7, 5]

[1, 3, 5, 9, 7, 5]

In [11]: # Example:

list1=['a','b','c']
list2=['x','y','z']
list3=list1+list2
print(list3) # ▶ ['a', 'b', 'c', 'x', 'y', 'z']

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 5/15


2/15/25, 7:40 PM 003_Python_List
['a', 'b', 'c', 'x', 'y', 'z']

In [12]: # Example:

list1=['a','b','c']
a='x'
print(list1+a) # ▶ TypeError: can only concatenate list (not "str") to list

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-4ed3868a9a2e> in <module>
3 list1=['a','b','c']
4 a='x'
----> 5 print(list1+a) # ▶ TypeError: can only concatenate list (not "str") to li
st

TypeError: can only concatenate list (not "str") to list

NOTE: + operator implies that both the operands passed must be list else
error will be shown.

The '*' operator repeats a list for the given number of times.

In [13]: # Example: Concatenating and repeating lists

odd = [1, 3, 5]

print(odd + [9, 7, 5]) # ▶ [1, 3, 5, 9, 7, 5]


print(["re"] * 3) # ▶ ['re', 're', 're']

[1, 3, 5, 9, 7, 5]
['re', 're', 're']

In [14]: # Example:

list1=['a','b','c']
print(list1*3) # ▶ quux ∵
print(["re"] * 3) # ▶ quux ∵

['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']


['re', 're', 're']

Furthermore, we can insert one item at a desired location by using the method insert()
or insert multiple items by squeezing it into an empty slice of a list.

In [15]: # Example: Demonstration of list insert() method

odd = [1, 9]
[Link](1,3)
print(odd) # ▶ [1, 3, 9]

odd[2:2] = [5, 7]
print(odd) # ▶ [1, 3, 5, 7, 9]

[1, 3, 9]
[1, 3, 5, 7, 9]

Delete/Remove List Elements

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 6/15


2/15/25, 7:40 PM 003_Python_List

We can delete one or more items from a list using the keyword del . It can even delete the
list entirely.

In [16]: # Example: Deleting list items

my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

del my_list[2] # delete one item


print(my_list) # ▶ ['p', 'r', 'b', 'l', 'e', 'm']

del my_list[1:5] # delete multiple items


print(my_list) # ▶ ['p', 'm']

del my_list # delete entire list


print(my_list) # ▶ NameError: name 'my_list' is not defined

['p', 'r', 'b', 'l', 'e', 'm']


['p', 'm']
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-16-b72af0bfcd83> in <module>
10
11 del my_list # delete entire list
---> 12 print(my_list) # ▶ NameError: name 'my_list' is not defined

NameError: name 'my_list' is not defined

In [17]: # Example:

list1=['a','b','c']
print("data in list : ",list1) # ▶ data in list : ['a', 'b', 'c']

del(list1[2])
print("new data in list : ",list1) # ▶ new data in list : ['a', 'b']

data in list : ['a', 'b', 'c']


new data in list : ['a', 'b']

We can use remove() method to remove the given item or pop() method to remove an
item at the given index.

The pop() method removes and returns the last item if the index is not provided. This
helps us implement lists as stacks (first in, last out data structure).

We can also use the clear() method to empty a list.

In [18]: # Example:

my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

print(my_list) # ▶ ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list.pop(1)) # ▶ 'o'
print(my_list) # ▶ ['r', 'b', 'l', 'e', 'm']
print(my_list.pop()) # ▶ 'm'
print(my_list) # ▶ ['r', 'b', 'l', 'e']

my_list.clear()
print(my_list) # ▶ []

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 7/15


2/15/25, 7:40 PM 003_Python_List
['r', 'o', 'b', 'l', 'e', 'm']
o
['r', 'b', 'l', 'e', 'm']
m
['r', 'b', 'l', 'e']
[]

Finally, we can also delete items in a list by assigning an empty list to a slice of elements.

In [19]: # Example:

my_list = ['p','r','o','b','l','e','m']

my_list[2:3] = []
print(my_list) # ▶ ['p', 'r', 'b', 'l', 'e', 'm']

my_list[2:-2] = []
print(my_list) # ▶ ['p', 'r', 'e', 'm']

['p', 'r', 'b', 'l', 'e', 'm']


['p', 'r', 'e', 'm']

Python Built-in List Functions


Built-in functions like all() , any() , sorted() , min() , max() , len() , cmp() ,
list() , etc. are commonly used with dictionaries to perform different tasks.

Functions Description

all() Returns True if all keys of the list are True.

any() Returns True if any key of the list is true. If the list is empty, return False .

sorted() Returns a new sorted list of elements in the list.

min() Returns the minimum value from the list given.

max() Returns the maximum value from the list given.

len() Returns number of elements in a list.

cmp() Compares items of two lists. (Not available in Python 3).

list() Takes sequence types and converts them to lists.

all(list) - The method all() method returns True when all


elements in the given iterable are true. If not, it returns False.
In [20]: # Example: How all() works for lists?

l = [1, 3, 4, 5]
print(all(l)) # ▶ True ∵ all values true

l = [0, False]
print(all(l)) # ▶ False ∵ all values false

l = [1, 3, 4, 0]
print(all(l)) # ▶ False ∵ one false value

l = [0, False, 5]
print(all(l)) # ▶ False ∵ one true value

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 8/15


2/15/25, 7:40 PM 003_Python_List

l = []
print(all(l)) # ▶ True ∵ empty iterable

True
False
False
False
True

any(list) - any() function returns True if any element of an


iterable is True. If not, any() returns False.
In [21]: # Example: True since 1,3 and 4 (at least one) is true

l = [1, 3, 4, 0]
print(any(l)) # ▶ True

l = [0, False]
print(any(l)) # ▶ False ∵ both are False

l = [0, False, 5]
print(any(l)) # ▶ True ∵ 5 is true

l = []
print(any(l)) # ▶ False ∵ iterable is empty

True
False
True
False

sorted(dict) - The sorted() function sorts the elements of a


given iterable in a specific order (either ascending or
descending) and returns the sorted iterable as a list.
In [22]: # Example: vowels list

py_list = ['e', 'a', 'u', 'o', 'i']


print(sorted(py_list)) # ▶ ['a', 'e', 'i', 'o', 'u']
print(sorted(py_list, reverse=True)) # ▶ ['u', 'o', 'i', 'e', 'a']

['a', 'e', 'i', 'o', 'u']


['u', 'o', 'i', 'e', 'a']

min(list) - this method is used to get min value from the


list. In Python3 lists element's type should be same otherwise
compiler throw type Error.
In [23]: # Example:

list1 = ['a','b','c']
list2 = [1,2,3]
list3=['a','b','c',1,2,3]

print(min(list1)) # ▶ a
print(min(list2)) # ▶ 1
print(min(list3)) # ▶ TypeError: '<' not supported between instances of 'int' and

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 9/15


2/15/25, 7:40 PM 003_Python_List
a
1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-9b450cb47d30> in <module>
7 print(min(list1)) # ▶ a
8 print(min(list2)) # ▶ 1
----> 9 print(min(list3)) # ▶ TypeError: '<' not supported between instances of
'int' and 'str'

TypeError: '<' not supported between instances of 'int' and 'str'

max(list) - The max() method returns the elements from


the list with maximum value.
In [24]: # Example:

list1 = ['a','b','c']
list2 = [1,2,3]
list3=['a','b','c',1,2,3]

print(max(list1)) # ▶ c
print(max(list2)) # ▶ 3
print(max(list3)) # ▶ TypeError: '>' not supported between instances of 'int' and

c
3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-8f0bbdfdf6e5> in <module>
7 print(max(list1)) # ▶ c
8 print(max(list2)) # ▶ 3
----> 9 print(max(list3)) # ▶ TypeError: '>' not supported between instances of
'int' and 'str'

TypeError: '>' not supported between instances of 'int' and 'str'

len(list) - The len() method returns the number of


elements in the list.
In [25]: # Example:

list1 = ['a','b','c']
list2 = []
list3=['a','b','c',1,2,3]

print(len(list1)) # ▶ 3
print(len(list2)) # ▶ 0
print(len(list3)) # ▶ 6

3
0
6

Python List Methods


Methods that are available with list objects in Python programming are tabulated below.
Some of the methods have already been used above.

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_Lis… 10/15


2/15/25, 7:40 PM 003_Python_List

Method Description

append() Add an element to the end of the list

extend() Add all elements of a list to the another list

insert() Insert an item at the defined index

remove() Removes an item from the list

pop() Removes and returns an element at the given index

clear() Removes all items from the list

index() Returns the index of the first matched item

count() Returns the count of the number of items passed as an argument

sort() Sort items in a list in ascending order

reverse() Reverse the order of items in the list

copy() Returns a shallow copy of the list

append() - The append() method adds an item to the end


of the list.
In [26]: # Example:

list1 =[1,2,3]
[Link](4)
[Link]('helloworld')
[Link](['a','b','c']) #append as single object
print(list1) # ▶ [1, 2, 3, 4, 'helloworld', ['a', 'b', 'c']]

[1, 2, 3, 4, 'helloworld', ['a', 'b', 'c']]

extend() - The extend() method adds all the elements of


an iterable (list, tuple, string etc.) to the end of the list.
In [27]: # Example:

list1 =[1,2,3]
[Link]([4])
[Link]('helloworld')
[Link](['a','b','c'])
print(list1) # ▶ [1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '

[1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 'a', 'b', 'c']

insert() - The insert() method inserts an element to the


list at the specified index.
In [28]: # Example:

list1 =['helloworld','python','java','c++',1,2,3]
[Link](3,'C#')
print(list1) # ▶ ['helloworld', 'python', 'java', 'C#', 'c++', 1, 2, 3]

['helloworld', 'python', 'java', 'C#', 'c++', 1, 2, 3]

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_Lis… 11/15


2/15/25, 7:40 PM 003_Python_List

remove() - The remove() method removes the first


matching element (which is passed as an argument) from the
list.
In [29]: # Example:

list1 =['helloworld','python','java','c++',1,2,3]
[Link]("java")
print(list1) # ▶ ['helloworld', 'python', 'c++', 1, 2, 3]
[Link](2)
print(list1) # ▶ ['helloworld', 'python', 'c++', 1, 3]

['helloworld', 'python', 'c++', 1, 2, 3]


['helloworld', 'python', 'c++', 1, 3]

pop() - The pop() method removes the item at the given


index from the list and returns the removed item.
In [30]: # Example:

list1 =['helloworld','python','java','c++',1,2,3]
[Link]() # pop last element
print(list1) # ▶ ['helloworld', 'python', 'java', 'c++', 1, 2]
[Link](2) # pop element with index 2
print(list1) # ▶ ['helloworld', 'python', 'c++', 1, 2]

['helloworld', 'python', 'java', 'c++', 1, 2]


['helloworld', 'python', 'c++', 1, 2]

clear() - The clear() method removes all items from the


list.
In [31]: list1 =['helloworld','python','java','c++',1,2,3]
[Link]()
print('list1:', list1) # ▶ list1: []

list1: []

index() - The index() method returns the index of the


specified element in the list.
In [32]: # Example:

list1 =['helloworld','python','java','c++',1,2,3]
print("index of java : ",[Link]('java')) # ▶ index of java : 2
print("index of 2 : ",[Link](2)) # ▶ index of 2 : 5

index of java : 2
index of 2 : 5

count() - The count() method returns the number of


times the specified element appears in the list.
In [33]: # Example:

list1 =[1,2,3,'a','b','c',1,2,3]
localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_Lis… 12/15
2/15/25, 7:40 PM 003_Python_List

print([Link](1)) # ▶ 2
print([Link]('b')) # ▶ 1
print([Link](4)) # ▶ 0

2
1
0

sort() - The sort() method sorts the elements of a given


list in a specific ascending or descending order.
In [34]: # Example:

list1 =[22,30,100,300,399]
list2=['z','ab','abc','a','b']
[Link]()
[Link]()
print(list1) # ▶ [22, 30, 100, 300, 399]

[Link](reverse=True)
print(list1) # ▶ [399, 300, 100, 30, 22]
print(list2) # ▶ ['a', 'ab', 'abc', 'b', 'z']

[22, 30, 100, 300, 399]


[399, 300, 100, 30, 22]
['a', 'ab', 'abc', 'b', 'z']

In [35]: # Example:

list3=['a','b',1,2]
[Link]()
print(list3) # ▶ TypeError: '<' not supported between instances of 'int' and 'str

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-b942612e6b6a> in <module>
2
3 list3=['a','b',1,2]
----> 4 [Link]()
5 print(list3) # ▶ TypeError: '<' not supported between instances of 'int'
and 'str'

TypeError: '<' not supported between instances of 'int' and 'str'

reverse() - The reverse() method reverses the elements


of the list.
In [36]: # Example:

list1 =['helloworld','python','java','c++',1,2,3]
[Link]()
print(list1) # ▶ [3, 2, 1, 'c++', 'java', 'python', 'helloworld']

[3, 2, 1, 'c++', 'java', 'python', 'helloworld']

copy() - The copy() method returns a shallow copy of the


list.

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_Lis… 13/15


2/15/25, 7:40 PM 003_Python_List

In [37]: list1 =['helloworld','python','java','c++',1,2,3]


list2 = [Link]()
print('list1:', list1) # ▶ list1: ['helloworld', 'python', 'java', 'c++', 1, 2, 3
print('list2:', list2) # ▶ list2: ['helloworld', 'python', 'java', 'c++', 1, 2, 3

list1: ['helloworld', 'python', 'java', 'c++', 1, 2, 3]


list2: ['helloworld', 'python', 'java', 'c++', 1, 2, 3]

Here is a complete list of all the built-in methods to work with List in Python.

List Comprehension: Elegant way to create new List


List comprehension is an elegant and concise way to create a new list from an existing list in
Python.

A list comprehension consists of an expression followed by for loop inside square brackets.

Here is an example to make a list with each item being increasing power of 2.

In [38]: pow2 = [2 ** x for x in range(10)]


print(pow2) # ▶ [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

This code is equivalent to:

In [39]: pow2 = []
for x in range(10):
[Link](2 ** x)
print(pow2) # ▶ [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

A list comprehension can optionally contain more for or if statements. An optional if


statement can filter out items for the new list. Here are some examples.

In [40]: pow2 = [2 ** x for x in range(10) if x > 5]


pow2 # ▶ [64, 128, 256, 512]

[64, 128, 256, 512]


Out[40]:

In [41]: odd = [x for x in range(20) if x % 2 == 1]


odd # ▶ [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]


Out[41]:

In [42]: [x+y for x in ['Python ','C '] for y in ['Language','Programming']]

['Python Language', 'Python Programming', 'C Language', 'C Programming']


Out[42]:

Other List Operations in Python

1. List Membership Test


We can test if an item exists in a list or not, using the keyword in .

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_Lis… 14/15


2/15/25, 7:40 PM 003_Python_List

In [43]: my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# Output: True
print('p' in my_list) # ▶ True

# Output: False
print('a' in my_list) # ▶ False

# Output: True
print('c' not in my_list) # ▶ True

True
False
True

2. Iterating Through a List


Using a for loop we can iterate through each item in a list.

In [44]: for fruit in ['apple','banana','mango']:


print("I like",fruit)

I like apple
I like banana
I like mango

3. Other List Operations in Python


Using a for loop we can iterate through each item in a list.

In [45]: # Example:

list1=['a','b','c',1,2,3]
for x in list1 :
print(x)

a
b
c
1
2
3

In [46]: for fruit in ['apple','banana','mango']:


print("I like",fruit)

I like apple
I like banana
I like mango

In [ ]:

localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_Lis… 15/15

Common questions

Powered by AI

Concatenating lists with mixed data types can lead to operations such as min() and max() raising TypeErrors, due to the inability to compare different types like integers and strings. This issue arises because these functions rely on comparison operators that are undefined between incompatible types. Consequently, such lists can only be processed by specific operations, limiting their utility and requiring additional handling or filtering to avoid runtime errors in type-sensitive operations .

The sort() method raises TypeErrors when trying to sort lists containing elements of different, incomparable data types, such as mixing strings and integers. Since the sort() method relies on comparison operations, which fail between incompatible types, a TypeError is inevitable. To avoid such errors, ensure that all elements are of a comparable type before calling sort(). Alternatively, custom sort keys can be defined to handle disparate types if mixed lists are necessary .

Python supports negative indexing, where an index of -1 refers to the last item, -2 to the second last item, and so on. This feature provides a flexible way to access elements relative to the end of a list. Slicing with negative indices follows the same rule, allowing sublists to be extracted from the end. However, misusing these indices can lead to IndexError if the accessed index exceeds the list boundaries. Moreover, using other data types like floats as indices will result in a TypeError .

List comprehensions provide a concise and expressive way to create lists in Python, allowing for the embedding of conditional and iterative logic within a single line of code. They enhance readability and reduce the need for verbose loops to initialize lists. However, their concise nature can obscure complex logic, making the code harder to understand for more intricate scenarios. Additionally, overusing comprehensions for deeply nested logic can affect the performance and maintainability of the code .

List membership tests using the 'in' keyword allow scripts to check the presence of elements in a list, providing a straightforward method for controlling flow based on data presence. These tests support operations such as filtering elements, ensuring data integrity before processing, or looping only through valid entries. Common use cases include conditional checks before element insertion or processing, avoiding duplicates, and confirming prerequisite data availability before executing dependent code blocks .

Optional if statements in list comprehensions act as filters, allowing only elements that meet certain conditions to be included in the resulting list. This provides the benefit of generating more concise and targeted lists directly from comprehension, without needing additional filtering code outside the comprehension. It leads to more efficient code execution, particularly when dealing with large datasets where refining data in a single pass significantly optimizes performance .

The extend() method adds all elements of an iterable to the end of a list. While using it with lists or tuples behaves predictably by appending their items, using it with strings will add each character individually as separate elements. A common pitfall with extend() is expecting it to append a whole iterable as a single item, similar to append(). Misunderstanding this difference can lead to unexpected list modifications. Another pitfall is the TypeError that arises when unintended non-iterables are passed to extend().

Lists in Python are mutable, meaning they can be modified after their creation without creating a new object. This affects memory management since elements within a list are references to objects stored elsewhere in memory, rather than being stored directly at the index. As a result, modifying a list element doesn't create a new list object, which enhances performance by reusing the existing list's memory space. The mutability also allows in-place modifications such as changing an element or range of elements, which differs from immutable data types like strings or tuples .

In Python, list slicing allows omitting the start or stop indices, defaulting to the start (beginning of the list) or end (end of the list) respectively. This feature offers great flexibility in list manipulation, enabling easy extraction of sublists without needing to determine precise index bounds. For instance, slicing [:end] extracts elements from the start to the specified endpoint, while slicing [start:] fetches elements from a given start index to the list's end. This simplifies handling lists whose size may vary dynamically .

Shallow copies, created using the copy() method, duplicate the top-level structure of a list but not the elements themselves. This means that while the copied list is independent of the original, changes to mutable elements within it (e.g., inner lists) will still reflect across copies because the references are copied, not the objects they point to. Thus, shallow copying can lead to unintended side effects if internal mutable objects are altered, requiring deep copies for full independence .

You might also like