Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Lists: Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic list

operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a tuple –
Nested tuples– Difference between lists and tuples. Dictionaries: Creating, Accessing, Updating
and Deleting Elements in a Dictionary – Dictionary Functions and Methods - Difference between
Lists and Dictionaries.

Python List
Python Lists are the most versatile compound data types. A Python list contains items separated by
commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays
in C. One difference between them is that all the items belonging to a Python list can be of different
data type where as C array can store elements related to a particular data type.

The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator. For example

How to create a list?


A Python list is generated in Python programming by putting all of the items (elements) inside square
brackets [], separated by commas. It can include an unlimited number of elements of various data types
(integer, float, string, etc.). Python Lists can also be created using the built-in list() method.

Example

my_list = []
print(my_list)

# creating list using square brackets


lang = ['Python', 'Java', 'C++', 'SQL']
print('List of languages are:', lang)

# creating list with mixed values


my_list = ['John', 23, 'Car', 45.2837]
print(my_list)

# nesting list inside a list


nested = ['Values', [1, 2, 3], ['Marks']]
print(nested)

# creating list using built-in function


print(list('Hello World'))
[]
List of languages are: ['Python', 'Java', 'C++', 'SQL']
['John', 23, 'Car', 45.2837]
['Values', [1, 2, 3], ['Marks']]
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Access List Elements


The elements of a list can be accessed in a variety of ways.

 List Index

Lists are ordered sequences of elements that, like all other ordered containers in Python, are indexed
with a starting index of 0. We supply the index (an integer) inside square brackets ([]) to access an
element in a list. Nested indexing is used to retrieve nested listings.

Attempting to access indexes beyond the limit will result in an IndexError. The index must be a
positive integer. We can’t use floats or other kinds because it will cause a TypeError.

Example

my_list = ['A', 'B', 'Car', 'Dog', 'Egg']

print('List value at index 1:', my_list[1])


print('List value at index 2:', my_list[2])
print('List value at index 4:', my_list[4])

# nesting list
nested = ['Values', [1, 2, 3], ['Marks']]
print(nested[0][0])
print(nested[1][0])
print(nested[1][2])
print(nested[2][0])

# IndexError exception
print(my_list[10])

Output:
List value at index 1: B
List value at index 2: Car
List value at index 4: Egg
V
1
3
Marks

ERROR!
Traceback (most recent call last):
File "<string>", line 20, in <module>
IndexError: list index out of range

Add/Change List Elements


Lists, unlike strings and tuples, are mutable, which means that their elements can be altered. There are
few methods by which we can add or change the elements inside the list. They are as follows –

 Using Assignment Operator

To alter an item or a range of elements, we can use the assignment operator ‘=’. We can change a list
item by putting the index or indexes in square brackets on the left side of the assignment operator (like
we access or slice a list) and the new values on the right.

Example

names = ['Ricky', 'Tim', 23, 100.23, 'Sam', 'Emily']


print('Original List:', names)

names[2] = 'Lily'
print('Updated List:', names)

names[3] = 'Han'
print('Updated List:', names)

names[1:] = ['A', 'B', 'C', 'D','E']


print('Updated List:', names)

Output:
Original List: ['Ricky', 'Tim', 23, 100.23, 'Sam', 'Emily']
Updated List: ['Ricky', 'Tim', 'Lily', 100.23, 'Sam', 'Emily']
Updated List: ['Ricky', 'Tim', 'Lily', 'Han', 'Sam', 'Emily']
Updated List: ['Ricky', 'A', 'B', 'C', 'D', 'E']

Basic List Operatiuons

Using append() & extend() method


The built-in append() function can be used to add elements to the List. The append() method can only
add one element to the list at a time. We can use the extend() function to add multiple elements to the
list.

Example

num = [1, 2, 3, 4]
print('Original List:', num)

num.append(5)
print(num)

num.extend([6, 7, 8])
print(num)

Ouptut:
Original List: [1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8]

 Using insert() method

We can insert one item at a time using the insert() method, or we can insert numerous things by
squeezing them into an empty slice of a list. Unlike the append() function, which accepts only one
argument, insert() function requires two arguments -> (position, value)

Example

num = [1, 2, 5, 6]
print('Original List:', num)

num.insert(2, 3)
print(num)

num.insert(3, 10)
print(num)

Output:
Original List: [1, 2, 5, 6]
[1, 2, 3, 5, 6]
[1, 2, 3, 10, 5, 6]
Delete/Remove List Elements
There are three methods for eliminating items from a list:

 Keyword del

Using the keyword del, we can remove one or more entries from a list. It has the ability to completely
remove the list.

num = [1, 2, 3, 4, 5, 6]
print('Original List:', num)

# delete one item


del num[2]
print(num)

# delete multiple items


del num[3:5]
print(num)

# delete entire list


del num
print(num)

Output:
Original List: [1, 2, 3, 4, 5, 6]
[1, 2, 4, 5, 6]
[1, 2, 4]
Traceback (most recent call last):
File "<string>", line 19, in <module>
ERROR!
NameError: name 'num' is not defined. Did you mean: 'sum'?

 Using remove() method

The Python remove() method returns None after removing the first matching element from the list. A
ValueError exception is thrown if the element is not found in the list.

num = ['p', 'y', 't', 'h', 'o', 'n']


print('Original List:', num)

num.remove('t')
print(num)
num.remove('n')
print(num)

Output:
Original List: ['p', 'y', 't', 'h', 'o', 'n']
['p', 'y', 'h', 'o', 'n']
['p', 'y', 'h', 'o']

 Using the pop() method

The pop() function can also be used to delete and return a list element. If no index is specified, the
Python pop() method removes and returns the list’s final item. When attempting to remove an index
that is outside the range of the list, an IndexError is raised.

tech = ['Mobile', 'Laptop', 'AI', '5G', 'ML']


print('Original List:', tech)

print('Item popped:', tech.pop())


print(tech)
print('Item popped:', tech.pop())
print(tech)
print('Item popped:', tech.pop(1))
print(tech)

Output:
Original List: ['Mobile', 'Laptop', 'AI', '5G', 'ML']
Item popped: ML
['Mobile', 'Laptop', 'AI', '5G']
Item popped: 5G
['Mobile', 'Laptop', 'AI']
Item popped: Laptop
['Mobile', 'AI']

 Assign an empty list to a slice

Also by assigning an empty list to a slice of elements, we can delete elements from a list. For example,
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print('Original List:', alpha)

alpha[2:5] = []
print(alpha)

Output:
Original List: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'f', 'g']

Python List Methods


The methods accessible with list objects in Python programming are listed below. They
are referred to as list.method().

Methods Description

append() Adds a single element to the end of the list

clear() Removes all the elements from the list

copy() Returns a shallow copy of the list

count() Returns the number of items specified as a parameter

extend() Adds multiple elements to the end of the list

index() Returns the index value of the first matched item

insert() Inserts an item at the specified index position

pop() Returns and removes an element at the specified index

remove() Removes a specified item from the list

reverse() Reverses the order of the entire list

sort() Sorts all the items in an ascending order


Python Tuples
Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists. For example –

Create Tuple

To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple

tp=('abcd', 786 , 2.23, 'john', 70.2)


print(tp)

output:

('abcd', 786, 2.23, 'john', 70.2)

Accessing elements from tuples:

You access the list items by referring to the index number:

Syntax: tuple_name[index_number]

tp=('abcd', 786 , 2.23, 'john', 70.2)


print(tp)
print("Access index element of 0:",tp[0])
print("Access index element of 3:",tp[2])

Output:
('abcd', 786, 2.23, 'john', 70.2)
Access index element of 0: abcd
Access index element of 3: 2.23

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the
list, and convert the list back into a tuple.
Syntax: Temp_variable=list(tupple_variable)

x = ("apple", "banana", "cherry")


print("tupple Value:",x)
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
print(y)

Output:
tupple Value: ('apple', 'banana', 'cherry')
('apple', 'kiwi', 'cherry')
['apple', 'kiwi', 'cherry']

Nested Tuples in Python


A nested tuple is a Python tuple that has been placed inside of another tuple. Let's have a
look at the following 8-element tuple.

tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))

This last element, which consists of three items enclosed in parenthesis, is known as a
nested tuple since it is contained inside another tuple.

employee = ((10, "Itika", 13000), (24, "Harry", 15294), (15, "Naill", 20001), (40, "Peter", 16395))
print(employee)
print(employee[0][1])
print(employee[1][1])
print(employee[2][1])
print(employee[3][1])

Ouptut:
((10, 'Itika', 13000), (24, 'Harry', 15294), (15, 'Naill', 20001), (40, 'Peter', 16395))
Itika
Harry
Naill
Peter
Difference between lists and tuples
The key difference between tuples and lists is that while tuples are immutable
objects, lists are mutable. This means tuples cannot be changed while lists can be modified.
Tuples are also more memory efficient than the lists.

Python Tuples vs. Lists

 Tuples and lists are both used to store collection of data


 Tuples and lists are both heterogeneous data types means that you can store any kind of data type.
 Tuples and lists are both ordered means the order in which you put the items are kept.
 Tuples and lists are both sequential data types so you can iterate over the items contained.
 Items of both tuples and lists can be accessed by an integer index operator, provided in square
brackets, [index].

 So…how do they differ?


 The key difference between tuples and lists is that while
the tuples are immutable objects, lists are mutable. This
means that tuples cannot be changed while lists can be
modified.

You might also like