0% found this document useful (0 votes)
18 views6 pages

List 1

Python

Uploaded by

ashousha11522
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)
18 views6 pages

List 1

Python

Uploaded by

ashousha11522
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
You are on page 1/ 6

Python collections (arrays)

There are four collection data types in the Python programming language: (list, tuple, set, dictionary)

List
Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are tuple, set, and dictionary, all with different qualities and usage. Lists are created
using square brackets:

Example: create a List.


thislist = [100, 50, 300]
print(thislist)

Output: [100, 50, 300]

List items
List items are indexed, the first item has index [0], the second item has index [1] etc.

List length: to determine how many items a list has, use the len() function:
Print the number of items in the list:
list_A = ["apple", "banana", "cherry"]
print(len(list_A))

Output: 3

List Items - Data Types: List items can be of any data type, or can contain different data types (string, int and
boolean).
list1 = ["apple", "banana", "cherry"] #The data types of list elements are string
list2 = [1, 5, 7, 9, 3] #The data types of list elements are string
list3 = [True, False, False] #The data types of list elements are string
list4 = ["abc", 34, True, 40, "male"] #A list with strings, integers and boolean values:

Access items: list items are indexed and you can access them by referring to the index number. The first item has
index 0, and the last item has index (length -1)
Example: print the second item of the list.

listB = [100, 50, 300,800,40,70]


print(listB [1])
Output: 50

print(listB[0])
Output: 100

print(listB[5])
Output: 70
1
print(listB
Output: [100, 50, 300, 800, 40, 70]

Negative indexing: negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last
item etc.

Example: print the last item of the list.


listB = [100, 50, 300,800,40,70]
print(listB [-1])
Output: 70

Range of indexes: you can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example: return the third, fourth, and fifth item:

A = [100, 50, 300,800,40,70]


print(A[2:5])

Output: [300, 800, 40]

Note: the search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item: This example returns the items from the beginning
to the fourth item.

A = [100, 50, 300,800,40,70]


print(A[:4])

Output: [100, 50, 300, 800]

By leaving out the end value, the range will go on to the end of the list. This example returns the items from 300 to
the end:

A = [100, 50, 300,800,40,70]


print(A[2:])

Output: [300, 800, 40, 70]

Range of negative indexes: specify negative indexes if you want to start the search from the end of the list:
This example returns the items from 300 (-4) to, but NOT including 70 (-1):

x = [100, 50, 300,800,40,70]


print(x[-4:-1])
Output: [300, 800, 40]

Change item value: to change the value of a specific item, refer to the index number:
Example: change the second item:

a = [100, 50, 300]


a[1] = 707
print(a)

2
Output: [100, 707, 300]

Change a range of item values: to change the value of items within a specific range, define a list with the new
values, and refer to the range of index numbers where you want to insert the new values:
Example: change the values 50 and 300 with the values 700 and 520.

b = [100, 50, 300,800,40,70]


b[1:3] = [700,520]
print(b)

Output: [100, 700, 520, 800, 40, 70]

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining
items will move accordingly.

Example: change the second value by replacing it with two new values:

z = [100, 50, 300]


z[1:2] = [60, 70]
print(z)

Output: [100, 60, 70, 300]


y = [100, 50, 300]
y[1] = [60, 70]
print(y)
Output: [100, 60, 70, 300]

Note: The length of the list will change when the number of items inserted does not match the number of items
replaced.
If you insert fewer items than you replace, the new items will be inserted where you specified, and the remaining
items will move accordingly:
Example: change the second and third value by replacing it with one value:

thislist = [100, 50, 300]


thislist[1:3] = [60]
print(thislist)

Output: [100, 60]

Loop Lists
Loop through a list: you can loop through the list items by using a for or while loop:
Example: print all items in the list, one by one.

listA = ["Apple", "Banana", "Orange"]


for x in listA:
print(x, end="---")

Output: Apple---Banana---Orange---

Example: print the squares of all items in the list, one by one.

3
listN = [1, 5, 7,8,10]
for x in listN:
print(x*x, end=" -")

Output: 1 -25 -49 -64 -100 –

Loop through the index numbers: you can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
Example: print all items by referring to their index number:
listA = ["Apple, "Banana", "Orange"]
for i in range(len(listA)):
print(listA[i])

Output:

Apple
Banana
Orange

listN = [100, 50, 300,800,40,70]


for i in range(5):
print(listN[i],end=",")

Output: 100,50,300,800,40,

Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by
referring to their indexes. Remember to increase the index by 1 after each iteration in while loop.

Example: print all items using a while loop to go through all the index numbers

listA = [80, 3, 20]


i = 0
while i < len(listA):
print(listA[i],end=" ")
i = i + 1

Output: 80 3 20

List methods
append(): adds an element at the end of the list
clear(): removes all the elements from the list
copy(): returns a copy of the list
count(): returns the number of elements with the specified value
extend(): add the elements of a list (or any iterable), to the end of the current list
index(): returns the index of the first element with the specified value
insert(): adds an element at the specified position
pop(): removes the element at the specified position
remove(): removes the item with the specified value
reverse(): reverses the order of the list
sort(): sorts the list on has a set of built-in methods that you can use on lists.

Append Items: To add an item to the end of the list, use the append() method.
4
Example: using the append() method to append an item:
listA = ["apple", "banana", "cherry"]
listA.append("orange")
print(listA)

Output: ['apple', 'banana', 'cherry', 'orange']

Insert Items: to insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example: insert an item as the second position:


listA = ["apple", "banana", "cherry"]
listA.insert(1,"orange")
print(listA)

Output: ['apple', 'orange', 'banana', 'cherry']

Note: As a result of the examples above, the lists will now contain 4 items.

Extend List: To append elements from another list to the current list, use the extend() method.
Example: add the elements of listB to listA:

listA = [10, 20,30]


listB = [100, 500, 1000]
listA.extend(listB)
print(listA)

Output: [10,20,30,100,500,1000]

The elements will be added to the end of the list.

Remove specified item: the remove() method removes the specified item.

Example: remove "banana":

listA = [10, 20,30]


listA.remove(20)
print(thislist)

Output: [10, 30]

Remove specified index: the pop() method removes the specified index.
Example: remove the second item:
listA = ["apple", "banana", "cherry"]
listA.pop(1)
print(listA)

Output: ['apple', 'cherry']

If you do not specify the index, the pop() method removes the last item.
5
Example: Remove the last item:
listA = ["apple", "banana", "cherry"]
listA.pop()
print(listA)

Output: ['apple', 'banana']

The del keyword also removes the specified index:

Example: remove the first item:

listA = ["apple", "banana", "cherry"]


del listA[0]
print(listA)

Output: ['banana', 'cherry']

The del keyword can also delete the list completely.

Example: delete the entire list.

listA = ["apple", "banana", "cherry"]


del listA
print(listA)

NameError: name 'listA' is not defined. Did you mean: 'list'?


Clear the list: the clear() method empties the list. The list still remains, but it has no content.

Example: clear the list content:

listA = ["apple", "banana", "cherry"]


listA.clear()
print(listA)
Output: []

Exercises

1) Write a program to sum all the items in a list.


2) Write a program to get the largest number from a list.
3) Write a program to count the number of elements in a list within a specified range.
4) Write a program to print how many negative numbers in a list.
5) Write a program to check whether an element given by the user exists in a given list.

You might also like