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

Python Lists Tuple and Dictionary

Uploaded by

hod.it
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)
18 views

Python Lists Tuple and Dictionary

Uploaded by

hod.it
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/ 8

PYTHON LISTS,TUPLE AND

DICTIONARY

LISTS
What is a List?

A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.

The important characteristics of Python lists are as follows:


 Lists are ordered.
 Lists can contain any arbitrary objects.
 List elements can be accessed by index.
 Lists can be nested to arbitrary depth.
 Lists are mutable.
 Lists are dynamic.

Example

To Create a List:

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


print(thislist)
It can have any number of items and they may be of different types (integer, float,
string etc.).
# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed data types


my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
To access Items

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

Example

Print the second item of the list:

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


print(thislist[1])
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])

# Output: o
print(my_list[2])

# Output: e
print(my_list[4])

# Error! Only integer can be used for indexing


# my_list[4.0]

# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a
print(n_list[0][1])

# Output: 5
print(n_list[1][3])
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.

my_list = ['p','r','o','b','e']

# Output: e
print(my_list[-1])

# Output: p
print(my_list[-5])

How to slice lists in Python?

We can access a range of items in a list by using the slicing operator (colon).

my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])

# elements beginning to 4th


print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])
To Change Item Value
To change the value of a specific item, refer to the index number:
Example

Change the second item:

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


thislist[1] = "blackcurrant"
print(thislist)
Loop Through a List

You can loop through the list items by using a for loop:

Example

Print all items in the list, one by one:

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


for x in thislist:
print(x)

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


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

To add Items using built in function

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

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


thislist.append("orange")
print(thislist)

To add an item at the specified index, use the insert() method:

Example

Insert an item as the second position:

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


thislist.insert(1, "orange")
print(thislist)
Remove Item There are several methods to remove items from a list:

Example

The remove() method removes the specified item:

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


thislist.remove("banana")
print(thislist)
Example

The pop() method removes the specified index, (or the last item if index is not
specified):

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


thislist.pop()
print(thislist)

The del keyword removes the specified index:


thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

The clear() method empties the list:


thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Copying Lists
a=[10,20,30,40,50]
b=a
print a
print b
a[3]=45
print a
print b
# the above method shows that a is copied to b and if something modified in
# a will get refleted in b
# when both lists to be treated separately then the following method will be used
b=list(a)
a[0]=12
print a
print b

List Functions
a=[10,20,30,40]
del a[1]
print a
a.pop(0) # pop and del will do the same.in del method index is mandatory
print a # in pop index is optinal if skipped then the last value will be deleted
k=a.pop()
print a
print k
# In case if we dont know the index position then the element will be removed with
the help of element (value) directly
a1=[100,200,300,400]
a1.remove(200)
print a1
a1.reverse()
print a1

z=['h','n','g','f','y']
z.sort()
print z
z.reverse()
print z
Program to eliminate duplicate values
d=[12,4,5,12,6,4,7,5]
list1 = []
for num in d:
if num not in list1:
list1.append(num)

print(list1)

Palindrome
a=['racecar','amma','sam','abba','ram']
for i in a:
if i[0]==i[-1]:
print(i)

Slicing: l=[12,3,4,5,6,7,8,9]

print(l[::]) [12, 3, 4, 5, 6, 7, 8, 9]
print(l[:]) [12, 3, 4, 5, 6, 7, 8, 9]
print(l[:3]) [12, 3, 4]
print(l[0:3]) [12, 3, 4]
print(l[1:5]) [3, 4, 5, 6]
print(l[::2]) [12, 4, 6, 8]
print(l[::-1]) [9, 8, 7, 6, 5, 4, 3, 12]
print(l[::-2]) [9, 7, 5, 3]
print(l[-5:]) [5, 6, 7, 8, 9]
print(l[-6:-2]) [4, 5, 6, 7]
print(l[6:1:-1]) [8, 7, 6, 5, 4]

Tuples
Tuples are immutable
#create a tuple
tuplex = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex)
t1=(12,3,5,6,66.7)
print (t1)
print len(t1)
print max(t1)
print (min(t1))
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

# packing-creating the tuple is called packing


# taking individual elements is called unpacking
t1=("nn",12,"kk","nn",67)
a,b,c,d,e=t1
#t1=a,b,c,d,e
print a
print b
print c
print d
print e

Dictionary
Unordered collection of data . Used to store data like a map
# You may also use different types other than strings for key/value pairs.
# Assigns an integer value to the 'key2' key.
d['key2'] = 1234567890

# Assigns a list value to the 'key3' key.


d['key3'] = ['a', 'b', 'c']

# Assigns a tuple value to the 'key4' key.


d['key4'] = (1, 2, 3)
# Even the key can be a type other than strings.
# The key here is an float.
d[98.6] = 'temperature'

# Prints the contents of the dictionary.


print ('d = ', d)
To get keys, values and items from the dictionary

sp = {}

sp["one"] = "uno"

sp["two"] = "dos"

for k in sp.keys():

print("Got key", k, "which maps to value", sp[k])


print list(sp.values()) # will print values

print list(sp.items()) # will print both keys and values

for (k,v) in sp.items():

print("Got",k,"that maps to",v)

other functions
d1={'name': 'Ram', 'roll': 101, 'mark': 80}

# len will find the length of the dictionary

print len(d1)

#del will delete the particular item . And the argument will be the key

del d["name"]

del d # will delete the entire dictionary

#del will delete the particular item . And the argument will be the key

d1.pop('roll')

print (dict1)

pop() can remove any item from a dictionary as long as you specify the key.

# update is used to merge 2 dictionaries


emp2={'Ravi':'Cricket','Suriya':'Football','Amrith':'Tennis'}

emp3={'Rama':'TT','Rini':'Basketball','Raghu':'Athletis'}

emp2.update(emp3)

print (emp2)

You might also like