0% found this document useful (0 votes)
1 views

Assignment 4

The document provides a comprehensive overview of Python lists, including their creation, indexing, slicing, and various methods for manipulation. It covers how to create lists, access elements using positive and negative indexing, and perform operations like appending, extending, removing, and sorting elements. Additionally, it includes practical examples and exercises to reinforce understanding of list operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Assignment 4

The document provides a comprehensive overview of Python lists, including their creation, indexing, slicing, and various methods for manipulation. It covers how to create lists, access elements using positive and negative indexing, and perform operations like appending, extending, removing, and sorting elements. Additionally, it includes practical examples and exercises to reinforce understanding of list operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Data Structures

1. List
Lists in Python are used to store collection of heterogeneous items i.e you can store items of different data types in a single list.

Lists are mutable, meaning that you can add, delete, or change elements in a flexible manner.
You can recognize lists by their square brackets [ and ] that hold elements, separated by a comma ,.
Lists are built into Python: you do not need to invoke them separately.

A) Creating Lists
In [7]: # . Create an empty list with name mylist
mylist= []

In [15]: # check the length of mylist


print("Length of mylist:", len(mylist))

Length of mylist: 0

In [19]: # Create an empty list L1 using list() constructor


L1 = list()

In [21]: # Dsiplay L1
print("L1:", L1)

L1: []

In [23]: # Create a list with 5 string values


languages=['Python','C','C++','Java','HTML']

In [25]: languages

Out[25]: ['Python', 'C', 'C++', 'Java', 'HTML']

In [27]: # create a list W using a range(0,20)


W = list(range(0, 20))

In [29]: # Dsiplay the elememts of W


W

Out[29]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In [31]: # create a list which contains [10,20] 5 times using replication operator
replicated_list = [10, 20] * 5

In [33]: replicated_list

Out[33]: [10, 20, 10, 20, 10, 20, 10, 20, 10, 20]

B) Accessing List Elements / Indexing


To get just one item from the list, you must specify its index. However, remember that indexing begins at 0. There are two types of Indexing

1. Positive Indexing
2. Negative Indexing

Positive Indexing

Positive indexing begins at 0 for the leftmost/first item, and then traverses right.

In [38]: # Create a list with 5-10 hetrogeneous type elements


L1=[True, False,100, 200, 3.145,'Python', None,'C']

In [ ]: # Retrieve the first element , then third element , then last element one by one

In [42]: # first element


L1[0]

Out[42]: True

In [44]: # third element


L1[2]

Out[44]: 100

In [46]: # Last element


L1[7]

Out[46]: 'C'

Negative Indexing

Contrary to positive indexing, negative indexing begins at -1 for the rightmost/last item, and then traverses left

In [50]: # Retrieve the last element using negative index


L1[-1]

Out[50]: 'C'

In [54]: #Retrieve the second last


#second last element is None so nothing will be displayed
L1[-2]

In [56]: #Retrieve the third last element


L1[-3]

Out[56]: 'Python'

C). Slicing
In [64]: # Consider the list below. You can create it using a range
l2=list(range(1,20))
print(l2)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In [66]: #Create a sublist which contains first 5 elements


sublist1 = l2[:5]
print(sublist1)

[1, 2, 3, 4, 5]

In [68]: #Create a list which contians elemenst from index 5 till index 10
sublist2 = l2[5:11]
print(sublist2)

[6, 7, 8, 9, 10, 11]

In [70]: #Create a sublist that contains elements from index 5 till the last element
sublist3 = l2[5:]
print(sublist3)

[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In [72]: #create a sublist that conatins last 5 elements using negative index
sublist4 = l2[-5:]
print(sublist4)

[15, 16, 17, 18, 19]

In [76]: #Create a sublist which displays all the number at even index from l2
sublist5 = l2[::2]
print(sublist5)

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

D) Useful Methods
In [43]: #Add an element at the end of the list
mylist=['C++' , 12, 20, 50.5 , True ]
list2=[10,20,30,40,50]

1. append()
To add an element at the end of a list

In [45]: # Add "python" at the end of mylist


mylist.append("python")

In [47]: #Display the elements of mylist


mylist

Out[47]: ['C++', 12, 20, 50.5, True, 'python']

In [49]: #Add 300 to mylist


mylist.append(300)

In [51]: #Dsiplay mylist


mylist

Out[51]: ['C++', 12, 20, 50.5, True, 'python', 300]

In [53]: # Add [10,20,30] using append to mylist


mylist.append([10, 20, 30])

In [55]: #Dsiplay mylist


mylist

Out[55]: ['C++', 12, 20, 50.5, True, 'python', 300, [10, 20, 30]]

In [57]: # Try to append multiple elements like append(10,20,30) to mylist


mylist.append(10,20,30)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[57], line 2
1 # Try to append multiple elements like append(10,20,30) to mylist
----> 2 mylist.append(10,20,30)

TypeError: list.append() takes exactly one argument (3 given)

In [59]: # TRy this one ... mylist.append("10,20,30")


mylist.append("10,20,30")

In [61]: # Dsiplay the elements of mylist


mylist

Out[61]: ['C++', 12, 20, 50.5, True, 'python', 300, [10, 20, 30], '10,20,30']

2. extend()
To append elements from another list to the current list, use the extend() method.

In [63]: #Add elements of list2 at the end of mylist


mylist.extend(list2)

In [65]: #Dsiplay the elements of mylist


mylist

Out[65]: ['C++',
12,
20,
50.5,
True,
'python',
300,
[10, 20, 30],
'10,20,30',
10,
20,
30,
40,
50]

In [67]: #Add True and False using extend to mylist


mylist.extend([True, False])

In [69]: #Dsiplay the elemsnt of mylist


mylist

Out[69]: ['C++',
12,
20,
50.5,
True,
'python',
300,
[10, 20, 30],
'10,20,30',
10,
20,
30,
40,
50,
True,
False]

3. remove()
The remove() method removes the first occurence of the specified item.

In [71]: #Dsiplay the elemsnt of mylist


mylist

Out[71]: ['C++',
12,
20,
50.5,
True,
'python',
300,
[10, 20, 30],
'10,20,30',
10,
20,
30,
40,
50,
True,
False]

In [73]: #Remove 20 from the list


mylist.remove(20)
mylist

Out[73]: ['C++',
12,
50.5,
True,
'python',
300,
[10, 20, 30],
'10,20,30',
10,
20,
30,
40,
50,
True,
False]

4. pop()
remove the element at the specified index , or the last element if index is not specified

In [128… languages=['C', 'C++','java','python','golang','python']

In [130… #Remove the last element from languages


languages.pop(5)

Out[130… 'python'

In [132… #Remove the 2nd element from languages


languages.pop(1)

Out[132… 'C++'

In [134… # Dsiplay the elements of languages


languages

Out[134… ['C', 'java', 'python', 'golang']

5. sort()
sorts the elements

In [138… l1=[23,6,89,45,3,15,90]
#Sort the elements in the list in ascending order
l1.sort()
l1

Out[138… [3, 6, 15, 23, 45, 89, 90]

In [142… #Sort the elements in reverse order


l1.sort(reverse=True)
l1

Out[142… [90, 89, 45, 23, 15, 6, 3]

6. index()
returns the index of the first occurence of a specified element

In [148… # 8. Return the index of 'java' from languages list


index_java = languages.index('java')
index_java

Out[148… 1

7. count()
Returns the numer of occurences of an element

In [150… # Count the occureneces of 'python' in languages


languages=['C', 'C++','java','python','golang','python']
#Count the occurences of 'python' in languages list
python_count = languages.count('python')
python_count

Out[150… 2

8. copy()
Creates a copy of a list

In [152… lang=languages.copy()

In [154… lang

Out[154… ['C', 'C++', 'java', 'python', 'golang', 'python']

9. reverse()
Reverses the order of a list

In [156… lang.reverse()

In [158… lang

Out[158… ['python', 'golang', 'python', 'java', 'C++', 'C']

10.clear()
Clear the contents of a list

In [160… languages.clear()

In [162… languages

Out[162… []

11. insert()
To insert a new list item, without replacing any of the existing values, we can use the insert() method.

In [11]: languages=['C', 'C#', 'C++', 'java', 'python', 'golang', 'python']

In [13]: languages.insert(1, "HTML")

In [15]: languages

Out[15]: ['C', 'HTML', 'C#', 'C++', 'java', 'python', 'golang', 'python']

In [17]: languages.insert(5, "PHP")

In [19]: languages

Out[19]: ['C', 'HTML', 'C#', 'C++', 'java', 'PHP', 'python', 'golang', 'python']

In [75]: mylist

Out[75]: ['C++',
12,
50.5,
True,
'python',
300,
[10, 20, 30],
'10,20,30',
10,
20,
30,
40,
50,
True,
False]

12. Modification

In [21]: ## Modification
languages

Out[21]: ['C', 'HTML', 'C#', 'C++', 'java', 'PHP', 'python', 'golang', 'python']

In [23]: i = languages.index('java') # Find index of 'java'


languages[i] = 'python'
languages

Out[23]: ['C', 'HTML', 'C#', 'C++', 'python', 'PHP', 'python', 'golang', 'python']

In [77]: mylist[0]="C" # replace the value at index 0 with C

In [79]: mylist

Out[79]: ['C',
12,
50.5,
True,
'python',
300,
[10, 20, 30],
'10,20,30',
10,
20,
30,
40,
50,
True,
False]

List Operators
+ Operator

In [209… human_languages=['English','Chinese','French']

In [211… languages

Out[211… ['C', 'HTML', 'C#', 'C++', 'python', 'PHP', 'python', 'golang', 'python']

In [215… languages_c=languages+human_languages

In [217… languages_c

Out[217… ['C',
'HTML',
'C#',
'C++',
'python',
'PHP',
'python',
'golang',
'python',
'English',
'Chinese',
'French']

in Operator

In [219… languages

Out[219… ['C', 'HTML', 'C#', 'C++', 'python', 'PHP', 'python', 'golang', 'python']

In [221… "C+++" not in languages

Out[221… True

In [223… if ('C' in languages_c ):


print( " C is present in the list")

C is present in the list

not in Operator

In [225… if ('C+++' not in languages_c ):


print( " C+++ is not present in the list")

C+++ is not present in the list

Practice Programs
In [85]: ### 1. Create a list of first 20 odd numbers and find their sum
l5= [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]
sum_off_odds= sum(l5)
print(l5)
print(sum_off_odds)

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]
400

In [9]: ### 2. Create a list of 10 integers and find the maximum/Minimum value and its index
L4=[10, 24, 5, 67,90,78,56,57,200,5, 3, 89]
max_value = max(L4)
min_value = min(L4)
max_index = L4.index(max_value)
min_index = L4.index(min_value)
print(L4)
print(max_index)
print(min_index)

[10, 24, 5, 67, 90, 78, 56, 57, 200, 5, 3, 89]


8
10

In [11]: # . Write a program that finds the maximum value and its position in a given list
L4 = [10, 24, 5, 67, 90, 78, 56, 57, 200, 5, 3, 89]
max_value = max(L4)
max_index = L4.index(max_value)

# Display the results


print("List:", L4)
print("Maximum value:", max_value)
print("Position (Index):", max_index)

List: [10, 24, 5, 67, 90, 78, 56, 57, 200, 5, 3, 89]
Maximum value: 200
Position (Index): 8

In [13]: ### 4. Assume the list has the following values


mylist=[10,20,30,54,56,67,89,34,56,10.5,100.70, 50.75,True,False,"C++","C","Python"]
#Write a computer program that count the number int , float , str and boolean type elements
int_count = 0
float_count = 0
str_count = 0
bool_count = 0

for item in mylist:


if type(item) == int and item is not True and item is not False:
int_count += 1
elif type(item) == float:
float_count += 1
elif type(item) == str:
str_count += 1
elif type(item) == bool:
bool_count += 1

print("Integers:", int_count)
print("Floats:", float_count)
print("Strings:", str_count)
print("Booleans:", bool_count)

Integers: 9
Floats: 3
Strings: 3
Booleans: 2

In [15]: # Sample list of words from the Oxford dictionary


oxford_list = ['the','and','i','to','a','was','it','my','went','we','on','he','in','they','then','of','said','had','so']
# Write a program which ask the user to enter a search word and the serach for that word in the list.
# It should return/ display the index if the word is found otherwise " word not found"
search_word = input("Enter a word to search: ").strip().lower()

# Check if the word is in the list


if search_word in oxford_list:
index = oxford_list.index(search_word)
print(f"Word found at index {index}")
else:
print("Word not found")

Word found at index 13

You might also like