List - 2
List - 2
LIST
For example,
numbers = [1, 2, 5]
print(numbers)
Output: [1, 2, 5]
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 = []
We can access elements of an array using the index number (0, 1, 2 …).
For example,
print(languages[0]) # Python
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.
Example
print(languages[-1]) # C++
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,
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5])
print(my_list[5:])
print(my_list[:])
Output
Here,
1. Using append()
For example,
numbers.append(32)
Output
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)
Output
List1: [2, 3, 5]
List2: [4, 6, 8]
List after append: [2, 3, 5, 4, 6, 8]
In Python, the del statement is used to remove one or more items from a list.
For example,
2. Using remove()
For example,
Method Description
extend() add items of lists and other iterables to the end of the list
insert() inserts an item at the specified index
For example,
Output
Python
Swift
C++
Here,
'C' is not present in languages, 'C' in languages evaluates to False.
'Python' is present in languages, 'Python' in languages evaluates to True.
Output
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.).
# Empty tuple
my_tuple = ()
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.
my_tuple = 1, 2, 3
my_tuple = 1, "Hello", 3.4
We can use the type() function to know which class a variable or a value belongs to.
var1 = ("hello")
print(type(var1)) # <class 'str'>
# 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'>
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.
2. Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on. For example,
We can access a range of items in a tuple by using the slicing operator colon :.
Output
Here,
print(my_tuple.count('p')) # prints 2
print(my_tuple.index('l')) # prints 3
Here,
Output
Python
Swift
C++
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.
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.
Output
In the above example, we have created different types of sets by placing all the elements
inside the curly braces {}.
To make a set without any elements, we use the set() function without any argument. For
example,
Output
Here,
Finally we have used the type() function to know which class empty_set and
empty_dictionary belong to.
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.
We cannot access or change an element of a set using indexing or slicing. Set data type does
not support it.
In Python, we use the add() method to add an item to a set. For example,
print('Initial Set:',numbers)
Output
In the above example, we have created a set named numbers. Notice the line,
numbers.add(32)
The update() method is used to update the set with items other collection types (lists, tuples,
sets, etc). For example,
companies.update(tech_companies)
print(companies)
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,
print('Initial Set:',languages)
Output
Here, we have used the discard() method to remove 'Java' from the languages set.
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.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
Output
Mango
Peach
Apple
even_numbers = {2,4,6,8}
print('Set:',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.
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}
Output
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}
Output
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}
Output
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
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Output
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}
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.
Method Description
intersection_update() Updates the set with the intersection of itself and another
update() Updates the set with the union of itself and others