Lists: are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.
Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable.
Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set.
Dictionary: in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
List, Tuple, Set, and Dictionary are the data structures in python that are used to store and organize the data in an efficient manner.
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:
Declaring and printing list
List items are ordered, changeable, and allow duplicate values.
When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
2.Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
Since lists are indexed, lists can have items with the same value
Accessing elements of List:
Ouput
Using negative integers
-1 index prints the last element of the list.
-2 index prints the second last item of the list and so on
Using a for loop :
Example 1
Example 2
The len()
function returns the number of items in an object.
When the object is a string, the len()
function returns the number of characters in the string.
Syntax
len(object)
Example
To add an item to the end of the list, use the append() method
To insert a list item at a specified index, use the insert()
method.
The insert()
method inserts an item at the specified index
mylist = ["apple","banana","cherry"] print(mylist) mylist.insert(1,"orange") print(mylist)
['apple', 'banana', 'cherry']
['apple', 'orange', 'banana', 'cherry']
The pop()
method removes the specified index.
mylist = ["apple","banana","cherry"] print(mylist) mylist.pop(1) print(mylist)
['apple', 'banana', 'cherry']
['apple', 'cherry']
If you do not specify the index, the pop()
method removes the last item.
mylist = ["apple","banana","cherry"] print(mylist) mylist.pop() print(mylist)
['apple', 'banana', 'cherry']
['apple', 'banana']
mylist = ["apple","banana","cherry"] print(mylist) item = mylist.pop() print(item) print(mylist)
It also returns the last item in the list
cherry
['apple', 'banana']
The remove()
method removes the specified item.
mylist = ["apple","banana","cherry"] print(mylist) mylist.remove("cherry") print(mylist)
['apple', 'banana', 'cherry']
['apple', 'banana']
The clear()
method empties the list.
The list still remains, but it has no content.
mylist = ["apple","banana","cherry"] print(mylist) mylist.clear() print(mylist)
['apple', 'banana', 'cherry']
[]
This function reverses the list
mylist = ["apple","banana","cherry"] print(mylist) mylist.reverse() print(mylist)
['apple', 'banana', 'cherry']
['cherry', 'banana', 'apple']
List objects have a sort()
method that will sort the list alphanumerically, ascending, by default
This updates the new list.
ie changes are made in the list.
mylist = [6,5,3,7,8] print(mylist) mylist.sort() print(mylist)
[6, 5, 3, 7, 8]
[3, 5, 6, 7, 8]
mylist = ["banana","cherry","apple"] print(mylist) mylist.sort() print(mylist)
['banana', 'cherry', 'apple']
['apple', 'banana', 'cherry']
This creates a new list instead of making changes to the new one.
mylist = ["banana","cherry","apple"] newlist = sorted(mylist) print(mylist) print(newlist)
['banana', 'cherry', 'apple']
['apple', 'banana', 'cherry']
Observe the difference carefully between sort() and sorted()
we did mylist.sort() in first case whereas we passed mylist as an argument in sorted method
newlist = sorted(mylist)
mylist = ["banana","cherry","apple"] *3 print(mylist)
['banana', 'cherry', 'apple', 'banana', 'cherry', 'apple', 'banana', 'cherry', 'apple']
mylist1 = ["banana","cherry","apple"] mylist2 = [1,2,3,4] mylistnew1 = mylist1+mylist2 print(mylistnew1) mylistnew2 = mylist2 + mylist1 print(mylistnew2)
['banana', 'cherry', 'apple', 1, 2, 3, 4]
[1, 2, 3, 4, 'banana', 'cherry', 'apple']
Observe that the list put first in addition has elements before the elements of the list put after the + operator
mylist1 = ["banana","cherry","apple"] mylist2 = [1,2,3,4] for x in mylist2: mylist1.append(x) print(mylist1)
['banana', 'cherry', 'apple', 1, 2, 3, 4]
By using + operator method we were creating a new list and storing elements of both lists into a new one but here we have stored the elemnts of mylist2 into mylist1
list_org = ["apple","lemon","orange"] list_cpy = list_org print(list_cpy) list_cpy.append("banana") print(list_cpy) print(list_org)
['apple', 'lemon', 'orange']
['apple', 'lemon', 'orange', 'banana']
['apple', 'lemon', 'orange', 'banana']
In this example we are cretaing a new list and copying the origianal list into new one.
But if we make changes to the new list they will also be applied to the original one
By using this method , the above mentioned pronlem is solved
list_org = ["apple","lemon","orange"] list_cpy = list_org.copy() print(list_cpy) list_cpy.append("banana") print(list_cpy) print(list_org)
['apple', 'lemon', 'orange']
['apple', 'lemon', 'orange', 'banana']
['apple', 'lemon', 'orange']
list_org = ["apple","lemon","orange"] list_cpy = list(list_org) print(list_cpy) list_cpy.append("banana") print(list_cpy) print(list_org)
['apple', 'lemon', 'orange']
['apple', 'lemon', 'orange', 'banana']
['apple', 'lemon', 'orange']
mylist = [1,2,3,4,5,6,7,8,9] a = mylist[1:5] print(a) # Here start value is index 1 # It will start from index 1 and slice the elements till index 4 #Note that index 5 written there is actually excluded b = mylist[:5] print(b) #if we do not write any start index it starts from index zero ie from the beginning of the list c = mylist[3:] print(c) #if we do not write the end index it ends at the last index d = mylist[::1] print(d) #this prints every item from the start till the end e = mylist[::2] print(e) #this prints every alternate item from start till end f = mylist[1 : 6 : 2] print(f) #this will print every altenate item from index 1 till index 6(excluded)
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
[4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
[2, 4, 6]
Tuples cannot be changed ones created
Ordered
Immutable
Allows duplicate elements
Created using () - paranthesis( they are optional)
mytuple = ("Nishant" ,19,"Nashik") print(mytuple)
('Nishant', 19, 'Nashik')
mytuple = ("Nishant") print(type(mytuple)) #When you have only one item in a tuple you need to put a #,(comma) after that one item. #This looks odd but that is how you declare a tuple with one item #otherwise the type of data structure will be considered as # string
<class 'str'>
mytuple = ("Nishant",) print(type(mytuple))
<class 'tuple'>
It is also possible to use the tuple() constructor to make a tuple.
mylist = ["Nishant",19,"Nashik"] mytuple = tuple(mylist) print(mytuple)
('Nishant', 19, 'Nashik')
You can access tuple elements by using the index of tuple elements
mytuple = ("Nishant" ,19,"Pune") print(mytuple[0]) print(mytuple[2]) print(mytuple[1])
Nishant
Pune
19
mytuple = ("Nishant" ,19,"Pune") print(mytuple[-1]) print(mytuple[-3]) print(mytuple[-2])
Pune
Nishant
19
mytuple = (1,2,3,4,5) for x in mytuple: print(x)
1
2
3
4
5
Finding if an item exists in the tuple or not
mytuple =(11,56,78,34,67) if 11 in mytuple: print("yes") else: print("no") if 71 in mytuple: print("yes") else: print("no")
yes
no
mytuple = ('a','e','i','o','u') print(len(mytuple))
5
mytuple = ('a','e','i','o','u') print(mytuple.index('i')) print(mytuple.index('u'))
2
4
mytuple = ('a','e','i','o','u') mylist = list(mytuple) print(mylist)
['a', 'e', 'i', 'o', 'u']
mytuple = (1,2,3,4,5,6,7,8,9) a = mytuple[1:5] print(a) # Here start value is index 1 # It will start from index 1 and slice the elements till index 4 #Note that index 5 written there is actually excluded b = mytuple[:5] print(b) #if we do not write any start index it starts from index zero ie from the beginning of the tuple c = mytuple[3:] print(c) #if we do not write the end index it ends at the last index d = mytuple[::1] print(d) #this prints every item from the start till the end e = mytuple[::2] print(e) #this prints every alternate item from start till end f = mytuple[1 : 6 : 2] print(f) #this will print every altenate item from index 1 till index 6(excluded)
(2, 3, 4, 5)
(1, 2, 3, 4, 5)
(4, 5, 6, 7, 8, 9)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
(1, 3, 5, 7, 9)
(2, 4, 6)
mytuple = "Nishant",19,"Pune" name,age,city = mytuple print(name) print(age) print(city)
Nishant
19
Pune
mytuple = (0,1,2,3,4) i1,*i2,i3 = mytuple print(i1) print(i3) print(*i2)
0
4
1 2 3
So well, how they differ then?
The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified.
Let’s further understand how this effect our code in terms of time and memory efficiency.
As lists are mutable, Python needs to allocate an extra memory block in case there is a need to extend the size of the list object after it is created. In contrary, as tuples are immutable and fixed size, Python allocates just the minimum memory block required for the data.
As a result, tuples are more memory efficient than the lists.
When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered
https://towardsdatascience.com/python-tuples-when-to-use-them-over-lists-75e443f9dcd7#:~:text=key%20takeaways%20are%3B-,The%20key%20difference%20between%20the%20tuples%20and%20lists%20is%20that,memory%20efficient%20than%20the%20lists.
Creating a dictionary
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} print(mydict) mydict1 = dict(name = "Harshada",Age = 18,City="Nashik") print(mydict1)
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}
{'name': 'Harshada', 'Age': 18, 'City': 'Nashik'}
Accessing items of dictionary
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} print(mydict) mydict1 = dict(name = "Harshada",Age = 18,City="Nashik") print(mydict1) value = mydict["name"] print(value) anothervalue = mydict1["Age"] print(anothervalue)
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}
{'name': 'Harshada', 'Age': 18, 'City': 'Nashik'}
Nishant
18
Accessing elemnts of dictionary and changing the values of keys
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} print(mydict) mydict["email"] = "nsihantkshirsagar@gmail.com" print(mydict) mydict["email" ] = "abc@xyz.com" print(mydict)
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik', 'email': 'nsihantkshirsagar@gmail.com'}
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik', 'email': 'abc@xyz.com'}
Deleting key value pairs
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} print(mydict) del mydict["name"] print(mydict)
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}
{'Age': '19', 'City': 'Nashik'}
pop()
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} print(mydict) mydict.pop("Age") print(mydict)
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}
{'name': 'Nishant', 'City': 'Nashik'}
popitem()
Removes the last key value pair from the dictionary
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} print(mydict) mydict.popitem() print(mydict)
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}
{'name': 'Nishant', 'Age': '19'}
finding if the given key exists in the dictionary or not
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} print(mydict) if "name" in mydict: print(mydict["name"]) else: print("error") try: print(mydict["Age"]) except: print("error")
{'name': 'Nishant', 'Age': '19', 'City': 'Nashik'}
Nishant
19
Looping over values and keys using for loop
mydict = {"name":"Nishant","Age":"19","City":"Nashik"} for key in mydict.keys(): print(key) for value in mydict.values(): print(value) for key,value in mydict.items(): print(key,value)
name
Age
City
Nishant
19
Nashik
name Nishant
Age 19
City Nashik
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"} my_dict_cpy = my_dict print(my_dict) my_dict_cpy["email"] = "abc@xyz.com" print(my_dict_cpy) print(my_dict)
{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}
{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}
{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"} my_dict_cpy = my_dict.copy() print(my_dict) my_dict_cpy["email"] = "abc@xyz.com" print(my_dict_cpy) print(my_dict)
{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}
{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}
{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"} my_dict_cpy = dict(my_dict) print(my_dict) my_dict_cpy["email"] = "abc@xyz.com" print(my_dict_cpy) print(my_dict)
{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}
{'name': 'Nishant', 'age': 19, 'city': 'Nashik', 'email': 'abc@xyz.com'}
{'name': 'Nishant', 'age': 19, 'city': 'Nashik'}
my_dict = {"name" : "Nishant", "age" : 19 ,"city" : "Nashik"} mydict_2 = {"name" : "Rahul", "college" : "Mit"} my_dict.update(mydict_2) print(my_dict)
{'name': 'Rahul', 'age': 19, 'city': 'Nashik', 'college': 'Mit'}
myset = {1,2,3,4,5} print(myset)
{1, 2, 3, 4, 5}
myset = set("Hello") print(myset)
{'e', 'l', 'H', 'o'}
myset ={} print(type(myset)) myset1 = set() print(type(myset1))
<class 'dict'>
<class 'set'>
myset ={1,2,3,4,5,6} print(myset) myset.add(7) myset.add(8) print(myset) myset.remove(3) myset.remove(6) print(myset) myset.discard(9) print(myset)
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 4, 5, 7, 8}
{1, 2, 4, 5, 7, 8}
myset ={1,2,3,4,5,6} print(myset.pop()) print(myset)
1
{2, 3, 4, 5, 6}
odds = {1,3,5,7} evens ={2,4,6,8} primes = {2,3,5,7} print(odds.union(evens)) print(odds.union(primes)) print(odds.intersection(evens)) print(odds.intersection(primes))
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 5, 7}
set()
{3, 5, 7}
setA = {1,2,3,6,7,8,9} setB = {1,2,3,10,11,12} print(setA.difference(setB)) print(setB.difference(setA))
{8, 9, 6, 7}
{10, 11, 12}
setA = {1,2,3,6,7,8,9} setB = {1,2,3,10,11,12} setA.update(setB) print(setA)
{1, 2, 3, 6, 7, 8, 9, 10, 11, 12}
setA = {1,2,3,6,7,8,9} setB = {1,2,3,10,11,12} setA.intersection_update(setB) print(setA)
{1, 2, 3}
setA = {1,2,3,6,7,8,9} setB = {1,2,3,10,11,12} setA.difference_update(setB) print(setA) setA.symmetric_difference_update(setB) print(setA)
{6, 7, 8, 9}
setA = {1,2,3,6,7,8,9} setB = {1,2,3,10,11,12} setA.symmetric_difference_update(setB) print(setA)
{6, 7, 8, 9, 10, 11, 12}
setA = {1,2,3,4,5,6} setB = {1,2,3} setC = {13,14,15} print(setA.issubset(setB)) print(setB.issubset(setA)) print(setA.issuperset(setB)) print(setA.isdisjoint(setB)) print(setA.isdisjoint(setC))
False
True
True
False
True
setA = frozenset([1,2,3,4,5]) print(setA)
frozenset({1, 2, 3, 4, 5})
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
my_str = "Hello World" print(my_str)
Hello World
Accessing character of string
my_str = "Hello World" char = my_str[4] print(my_str) print(char) char_negative = my_str
Hello World
o
Using n
Last Updated:
Summarize & share videos seamlessly
Loading...