[go: up one dir, main page]

0% found this document useful (0 votes)
17 views21 pages

List - 2

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

List - 2

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

UNIT – 2

LIST

List is a collection of ordered items.

Create a Python List


A list is created in Python by placing items inside [], separated by commas .

For example,

# A list with 3 integers

numbers = [1, 2, 5]

print(numbers)

Output: [1, 2, 5]

Here, we have created a list named numbers with 3 integer items.

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

# empty list
my_list = []

# list with mixed data types


my_list = [1, "Hello", 3.4]

Access Python List Elements


In Python, each item in a list is associated with a number. The number is known as a list
index.

We can access elements of an array using the index number (0, 1, 2 …).

For example,

languages = ["Python", "Swift", "C++"]

# access item at index 0

print(languages[0]) # Python

# access item at index 2

print(languages[2]) # C++
In the above example, we have created a list named languages.

Here, we can see each list item is associated with the index number. And, we have used the index
number to access the items.

Negative Indexing in Python


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.

Example

languages = ["Python", "Swift", "C++"]

# access item at index 0

print(languages[-1]) # C++

# access item at index 2

print(languages[-3]) # Python
Slicing of a Python List
In Python it is possible to access a section of items from the list using the slicing operator :,
not just a single item.

For example,

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# items from index 2 to index 4

print(my_list[2:5])

# items from index 5 to end

print(my_list[5:])

# items beginning to end

print(my_list[:])

Output

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


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

Here,

 my_list[2:5] returns a list with items from index 2 to index 4.


 my_list[5:] returns a list with items from index 5 to the end.
 my_list[:] returns all list items
Add Elements to a Python List
Python List provides different methods to add items to a list.

1. Using append()

The append() method adds an item at the end of the list.

For example,

numbers = [21, 34, 54, 12]

print("Before Append:", numbers)

# using append method

numbers.append(32)

print("After Append:", numbers)

Output

Before Append: [21, 34, 54, 12]


After Append: [21, 34, 54, 12, 32]

Here, append() adds 32 at the end of the array.

2. Using extend()

The extend() method to add all items of one list to another. For example,

prime_numbers = [2, 3, 5]
print("List1:", prime_numbers)

even_numbers = [4, 6, 8]
print("List2:", even_numbers)

# join two lists


prime_numbers.extend(even_numbers)

print("List after append:", prime_numbers)

Output

List1: [2, 3, 5]
List2: [4, 6, 8]
List after append: [2, 3, 5, 4, 6, 8]

Change List Items


Python lists are mutable. Meaning lists are changeable. And, we can change items of a list by
assigning new values using = operator. For example,

languages = ['Python', 'Swift', 'C++']

# changing the third item to 'C'


languages[2] = 'C'

print(languages) # ['Python', 'Swift', 'C']

Remove an Item From a List


1. Using del()

In Python, the del statement is used to remove one or more items from a list.

For example,

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the second item


del languages[1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the last item


del languages[-1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']

# delete first two items


del languages[0 : 2] # ['C', 'Java', 'Rust']
print(languages)

2. Using remove()

The remove() method is use to delete a list item.

For example,

languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# remove 'Python' from the list


languages.remove('Python')

print(languages) # ['Swift', 'C++', 'C', 'Java', 'Rust', 'R']

Python List Methods


Python has many useful list methods that makes it really easy to work with lists.

Method Description

append() add an item to the end of the list

extend() add items of lists and other iterables to the end of the list
insert() inserts an item at the specified index

remove() removes item present at the given index

pop() returns and removes item present 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 specified item in the list

sort() sort the list in ascending/descending order

reverse() reverses the item of the list

copy() returns the shallow copy of the list

Iterating through a List


The for loop is used to iterate over the elements of a list.

For example,

languages = ['Python', 'Swift', 'C++']

# iterating through the list


for language in languages:
print(language)

Output

Python
Swift
C++

Check if an Item Exists in the Python List


We use the in keyword to check if an item exists in the list or not. For example,

languages = ['Python', 'Swift', 'C++']

print('C' in languages) # False


print('Python' in languages) # True

Here,
 'C' is not present in languages, 'C' in languages evaluates to False.
 'Python' is present in languages, 'Python' in languages evaluates to True.

Python List Length


In Python, we use the len() function to find the number of elements present in a list. For
example,

languages = ['Python', 'Swift', 'C++']

print("List: ", languages)

print("Total Elements: ", len(languages)) # 3

Output

List: ['Python', 'Swift', 'C++']


Total Elements: 3

TUPLE

A tuple in Python is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas we can change the elements of a list.

Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.

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

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Run Code

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

In the above example, we have created different types of tuples and stored different data
items inside them.

As mentioned earlier, we can also create tuples without using parentheses:

my_tuple = 1, 2, 3
my_tuple = 1, "Hello", 3.4

Create a Python Tuple With one Element


In Python, creating a tuple with one element is a bit tricky. Having one element within
parentheses is not enough.

We will need a trailing comma to indicate that it is a tuple,

var1 = ("Hello") # string


var2 = ("Hello",) # tuple

We can use the type() function to know which class a variable or a value belongs to.

var1 = ("hello")
print(type(var1)) # <class 'str'>

# Creating a tuple having one element


var2 = ("hello",)
print(type(var2)) # <class 'tuple'>

# Parentheses is optional
var3 = "hello",
print(type(var3)) # <class 'tuple'>
Run Code

Here,

 ("hello") is a string so type() returns str as class of var1 i.e. <class 'str'>
 ("hello",) and "hello", both are tuples so type() returns tuple as class of var1 i.e.
<class 'tuple'>

Access Python Tuple Elements


Like a list, each element of a tuple is represented by index numbers (0, 1, ...) where the first
element is at index 0.

We use the index number to access tuple elements. For example,

1. Indexing

We can use the index operator [] to access an item in a tuple, where the index starts from 0.

So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside
of the tuple index range( 6,7,... in this example) will raise an IndexError.

The index must be an integer, so we cannot use float or other types. This will result in
TypeError.

Likewise, nested tuples are accessed using nested indexing, as shown in the example below.

# accessing tuple elements using indexing


letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")

print(letters[0]) # prints "p"


print(letters[5]) # prints "a"

In the above example,

 letters[0] - accesses the first element


 letters[5] - accesses the sixth element

2. 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. For example,

# accessing tuple elements using negative indexing


letters = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(letters[-1]) # prints 'z'


print(letters[-3]) # prints 'm'

In the above example,

 letters[-1] - accesses last element


 letters[-3] - accesses third last element
3. Slicing

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

# accessing tuple elements using slicing


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# elements 2nd to 4th index


print(my_tuple[1:4]) # prints ('r', 'o', 'g')
# elements beginning to 2nd
print(my_tuple[:-7]) # prints ('p', 'r')

# elements 8th to end


print(my_tuple[7:]) # prints ('i', 'z')

# elements beginning to end


print(my_tuple[:]) # Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Output

('r', 'o', 'g')


('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Here,

 my_tuple[1:4] returns a tuple with elements from index 1 to index 3.


 my_tuple[:-7] returns a tuple with elements from beginning to index 2.
 my_tuple[7:] returns a tuple with elements from index 7 to the end.
 my_tuple[:] returns all tuple items.

Python Tuple Methods


In Python ,methods that add items or remove items are not available with tuple. Only the
following two methods are available.

Some examples of Python tuple methods:

my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 3

Here,

 my_tuple.count('p') - counts total number of 'p' in my_tuple


 my_tuple.index('l') - returns the first occurrence of 'l' in my_tuple

Iterating through a Tuple in Python


The for loop to iterate over the elements of a tuple. For example,

languages = ('Python', 'Swift', 'C++')

# iterating through the tuple


for language in languages:
print(language)

Output

Python
Swift
C++

Advantages of Tuple over List in Python


Since tuples are quite similar to lists, both of them are used in similar situations.

However, there are certain advantages of implementing a tuple over a list:

 We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
 Since tuples are immutable, iterating through a tuple is faster than with a list. So there
is a slight performance boost.
 Tuples that contain immutable elements can be used as a key for a dictionary. With
lists, this is not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

SETS

A set is a collection of unique data. That is, elements of a set cannot be duplicate.

Create a Set in Python


In Python, we create sets by placing all the elements inside curly braces {}, separated by
comma.

A set can have any number of items and they may be of different types (integer, float, tuple,
string etc.). But a set cannot have mutable elements like list or dictionaries as its elements.

Let's see an example,

# create a set of integer type


student_id = {112, 114, 116, 118, 115}
print('Student ID:', student_id)

# create a set of string type


vowel_letters = {'a', 'e', 'i', 'o', 'u'}
print('Vowel Letters:', vowel_letters)
# create a set of mixed data types
mixed_set = {'Hello', 101, -2, 'Bye'}
print('Set of mixed data types:', mixed_set)

Output

Student ID: {112, 114, 115, 116, 118}


Vowel Letters: {'u', 'a', 'e', 'i', 'o'}
Set of mixed data types: {'Hello', 'Bye', 101, -2}

In the above example, we have created different types of sets by placing all the elements
inside the curly braces {}.

Create an Empty Set in Python


Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in
Python.

To make a set without any elements, we use the set() function without any argument. For
example,

# create an empty set


empty_set = set()

# create an empty dictionary


empty_dictionary = { }

# check data type of empty_set


print('Data type of empty_set:', type(empty_set))

# check data type of dictionary_set


print('Data type of empty_dictionary', type(empty_dictionary))

Output

Data type of empty_set: <class 'set'>


Data type of empty_dictionary <class 'dict'>

Here,

 empty_set - an empty set created using set()


 empty_dictionary - an empty dictionary created using {}

Finally we have used the type() function to know which class empty_set and
empty_dictionary belong to.

Duplicate Items in a Set


Let's see what will happen if we try to include duplicate items in a set.

numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}

Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.

Add and Update Set Items in Python


Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. Set data type does
not support it.

Add Items to a Set in Python

In Python, we use the add() method to add an item to a set. For example,

numbers = {21, 34, 54, 12}

print('Initial Set:',numbers)

# using add() method


numbers.add(32)

print('Updated Set:', numbers)

Output

Initial Set: {34, 12, 21, 54}


Updated Set: {32, 34, 12, 21, 54}

In the above example, we have created a set named numbers. Notice the line,

numbers.add(32)

Here, add() adds 32 to our set.

Update Python Set

The update() method is used to update the set with items other collection types (lists, tuples,
sets, etc). For example,

companies = {'Lacoste', 'Ralph Lauren'}


tech_companies = ['apple', 'google', 'apple']

companies.update(tech_companies)

print(companies)

# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}

Here, all the unique elements of tech_companies are added to the companies set.
Remove an Element from a Set
We use the discard() method to remove the specified element from a set. For example,

languages = {'Swift', 'Java', 'Python'}

print('Initial Set:',languages)

# remove 'Java' from a set


removedValue = languages.discard('Java')

print('Set after remove():', languages)

Output

Initial Set: {'Python', 'Swift', 'Java'}


Set after remove(): {'Python', 'Swift'}

Here, we have used the discard() method to remove 'Java' from the languages set.

Built-in Functions with Set


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

Function Description

all() Returns True if all elements of the set are true (or if the set is empty).

any() Returns True if any element of the set is true. If the set is empty, returns False.

Returns an enumerate object. It contains the index and value for all the items of the
enumerate()
set as a pair.

len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

sorted() Returns a new sorted list from elements in the set(does not sort the set itself).

sum() Returns the sum of all elements in the set.

Iterate Over a Set in Python


fruits = {"Apple", "Peach", "Mango"}

# for loop to access each fruits


for fruit in fruits:
print(fruit)

Output

Mango
Peach
Apple

Find Number of Set Elements


We can use the len() method to find the number of elements present in a Set. For example,

even_numbers = {2,4,6,8}
print('Set:',even_numbers)

# find number of elements


print('Total Elements:', len(even_numbers))

Output

Set: {8, 2, 4, 6}
Total Elements: 4

Here, we have used the len() method to find the number of elements present in a Set.

Python Set Operations


Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, subtraction, and symmetric difference.

Union of Two Sets

The union of two sets A and B include all the elements of set A and B.
Set Union in Python

We use the | operator or the union() method to perform the set union operation. For
example,

# first set
A = {1, 3, 5}

# second set
B = {0, 2, 4}

# perform union operation using |


print('Union using |:', A | B)

# perform union operation using union()


print('Union using union():', A.union(B))
Run Code

Output

Union using |: {0, 1, 2, 3, 4, 5}


Union using union(): {0, 1, 2, 3, 4, 5}

Note: A|B and union() is equivalent to A ⋃ B set operation.

Set Intersection

The intersection of two sets A and B include the common elements between set A and B.
Set Intersection in Python

In Python, we use the & operator or the intersection() method to perform the set
intersection operation. For example,

# first set
A = {1, 3, 5}

# second set
B = {1, 2, 3}

# perform intersection operation using &


print('Intersection using &:', A & B)

# perform intersection operation using intersection()


print('Intersection using intersection():', A.intersection(B))

Output

Intersection using &: {1, 3}


Intersection using intersection(): {1, 3}

Note: A&B and intersection() is equivalent to A ⋂ B set operation.

Difference between Two Sets

The difference between two sets A and B include elements of set A that are not present on set
B.
Set Difference in Python

We use the - operator or the difference() method to perform the difference between two
sets. For example,

# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &


print('Difference using &:', A - B)

# perform difference operation using difference()


print('Difference using difference():', A.difference(B))

Output

Difference using &: {3, 5}


Difference using difference(): {3, 5}

Note: A - B and A.difference(B) is equivalent to A - B set operation.

Set Symmetric Difference

The symmetric difference between two sets A and B includes all elements of A and B without
the common elements.
Set Symmetric Difference in Python

In Python, we use the ^ operator or the symmetric_difference() method to perform


symmetric difference between two sets. For example,

# first set
A = {2, 3, 5}

# second set
B = {1, 2, 6}

# perform difference operation using &


print('using ^:', A ^ B)

# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))

Output

using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}

Check if two sets are equal


We can use the == operator to check whether two sets are equal or not. For example,

# first set
A = {1, 3, 5}

# second set
B = {3, 5, 1}

# perform difference operation using &


if A == B:
print('Set A and Set B are equal')
else:
print('Set A and Set B are not equal')
Output

Set A and Set B are equal

In the above example, A and B have the same elements, so the condition

if A == B

evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the
if is executed.

Other Python Set Methods


There are many set methods, some of which we have already used above. Here is a list of all
the methods that are available with the set objects:

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

Removes an element from the set if it is a member. (Do nothing if


discard()
the element is not in set)

intersection() Returns the intersection of two sets as a new set

intersection_update() Updates the set with the intersection of itself and another

isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element. Raises KeyError if


pop()
the set is empty

Removes an element from the set. If the element is not a member,


remove()
raises a KeyError

symmetric_difference() Returns the symmetric difference of two sets as a new set


symmetric_difference_update() Updates a set with the symmetric difference of itself and another

union() Returns the union of sets in a new set

update() Updates the set with the union of itself and others

You might also like