In this article, we'll learn everything about Python lists, how they are created, slicing of a list, adding or removing elements from them and so on. List is one of the most frequently used and very versatile data types used in Python.
How to create a list?
In Python programming, a list is created by placing all the items (elements) inside square brackets [] , separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.)
A list can also have another list as an item. This is called a nested list.
How to access elements from a list?
There are various ways in which we can access the elements of a list
List Index
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError . The index must be an integer. We can't use float or other types, this will result in TypeError.
Nested lists are accessed using nested indexing.
# List indexingmy_list = ['p','r','o','b','e']# Output: pprint(my_list[0])# Output: oprint(my_list[2])# Output: eprint(my_list[4])# Nested Listn_list = ["Happy", [2,0,1,5]]# Nested indexingprint(n_list[0][1])print(n_list[1][3])# Error! Only integer can be used for indexingprint(my_list[4.0])
p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float
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.
# Negative indexing in listsmy_list = ['p','r','o','b','e']print(my_list[-1])print(my_list[-5])
e
p
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator : (colon).
:(colon).# List slicing in Pythonmy_list = ['p','r','o','g','r','a','m','i','z']# elements 3rd to 5thprint(my_list[2:5])# elements beginning to 4thprint(my_list[:-5])# elements 6th to endprint(my_list[5:])# elements beginning to endprint(my_list[:])
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need two indices that will slice that portion from the list.
Add/Change List Elements
Lists are mutable, meaning their elements can be changed unlike string or tuple.
We can use the assignment operator ( = ) to change an item or a range of items.
# Correcting mistake values in a listodd = [2,4,6,8]# change the 1st item odd[0]=1print(odd)# change 2nd to 4th itemsodd[1:4]= [3,5,7] print(odd)
[1, 4, 6, 8]
[1, 3, 5, 7]
We can add one item to a list using the append() method or add several items using extend() method.
# Appending and Extending lists in Pythonodd = [1,3,5]odd.append(7)print(odd)odd.extend([9, 11, 13])print(odd)
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.
# Demonstration of list insert() methododd = [1,9]odd.insert(1,3)print(odd)odd[2:2]= [5,7]print(odd)
[1, 3, 9]
[1, 3, 5, 7, 9]
Delete/Remove List Elements
We can delete one or more items from a list using the keyword del . It can even delete the list entirely
# Deleting list itemsmy_list = ['p','r','o','b','l','e','m']# delete one itemdel my_list[2]print(my_list)# delete multiple itemsdel my_list[1:5]print(my_list)# delete entire listdel my_list# Error: List not definedprint(my_list)
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
Traceback (most recent call last):
File "<string>", line 18, in <module>
NameError: name 'my_list' is not defined
We can use remove() method to remove the given item or pop() method to remove an item at the given index.
The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure).
We can also use the clear() method to empty a list.
List comprehension is an elegant and concise way to create a new list from an existing list in Python.
A list comprehension consists of an expression followed by for statement inside square brackets.
Here is an example to make a list with each item being increasing power of 2.
pow2 = [2** x for x inrange(10)]print(pow2)
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
This code is equivalent to:
pow2 = []for x inrange(10): pow2.append(2** x)
A list comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. Here are some examples.
>>> pow2 = [2** x for x inrange(10)if x >5]>>> pow2[64,128,256,512]>>> odd = [x for x inrange(20)if x %2==1]>>> odd[1,3,5,7,9,11,13,15,17,19]>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]['Python Language','Python Programming','C Language','C Programming']
Other List Operations in Python
List Membership Test
We can test if an item exists in a list or not, using the keyword in.
Using a for loop we can iterate through each item in a list.
for fruit in ['apple','banana','mango']:print("I like",fruit)
I like apple
I like banana
I like mango
Python Tuple
In this article, you'll learn everything about Python tuples. More specifically, what are tuples, how to create them, when to use them and various methods you should be familiar with.
A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas we can change the elements of a list.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses () , separated by commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
# Different types of tuples# Empty tuplemy_tuple = ()print(my_tuple)# Tuple having integersmy_tuple = (1,2,3)print(my_tuple)# tuple with mixed datatypesmy_tuple = (1,"Hello",3.4)print(my_tuple)# nested tuplemy_tuple = ("mouse", [8,4,6], (1,2,3))print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.
my_tuple =3,4.6,"dog"print(my_tuple)# tuple unpacking is also possiblea, b, c = my_tupleprint(a)# 3print(b)# 4.6print(c)# dog
(3, 4.6, 'dog')
3
4.6
dog
Creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in fact, a tuple.
my_tuple = ("hello")print(type(my_tuple))# <class 'str'># Creating a tuple having one elementmy_tuple = ("hello",)print(type(my_tuple))# <class 'tuple'># Parentheses is optionalmy_tuple ="hello",print(type(my_tuple))# <class 'tuple'>
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Access Tuple Elements
There are various ways in which we can access the elements of a tuple.
1.Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError .
The index must be an integer, so we cannot use float or other types. This will result in TypeError .
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
# Accessing tuple elements using indexingmy_tuple = ('p','e','r','m','i','t')print(my_tuple[0])# 'p' print(my_tuple[5])# 't'# IndexError: list index out of range# print(my_tuple[6])# Index must be an integer# TypeError: list indices must be integers, not float# my_tuple[2.0]# nested tuplen_tuple = ("mouse", [8,4,6], (1,2,3))# nested indexprint(n_tuple[0][3])# 's'print(n_tuple[1][1])# 4
p
t
s
4
2.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.
We can access a range of items in a tuple by using the slicing operator colon:
# Accessing tuple elements using slicingmy_tuple = ('p','r','o','g','r','a','m','i','z')# elements 2nd to 4th# Output: ('r', 'o', 'g')print(my_tuple[1:4])# elements beginning to 2nd# Output: ('p', 'r')print(my_tuple[:-7])# elements 8th to end# Output: ('i', 'z')print(my_tuple[7:])# elements beginning to end# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')print(my_tuple[:])
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need the index that will slice the portion from the tuple.
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is itself a mutable data type like list, its nested items can be changed.
We can also assign a tuple to different values (reassignment).
# Changing tuple valuesmy_tuple = (4,2,3, [6,5])# TypeError: 'tuple' object does not support item assignment# my_tuple[1] = 9# However, item of mutable element can be changedmy_tuple[3][0] =9# Output: (4, 2, 3, [9, 5])print(my_tuple)# Tuples can be reassignedmy_tuple = ('p','r','o','g','r','a','m','i','z')# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')print(my_tuple)
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del .
# Deleting tuplesmy_tuple = ('p','r','o','g','r','a','m','i','z')# can't delete items# TypeError: 'tuple' object doesn't support item deletion# del my_tuple[3]# Can delete an entire tupledel my_tuple# NameError: name 'my_tuple' is not definedprint(my_tuple)
Traceback (most recent call last):
File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two methods are available.
We can test if an item exists in a tuple or not, using the keyword in
# Membership test in tuplemy_tuple = ('a','p','p','l','e',)# In operationprint('a'in my_tuple)print('b'in my_tuple)# Not in operationprint('g'notin my_tuple)
True
False
True
2. Iterating Through a Tuple
We can use a for loop to iterate through each item in a tuple.
# Using a for loop to iterate through a tuplefor name in ('John','Kate'):print("Hello", name)
Hello John
Hello Kate
Advantages of Tuple over List
Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages:
We generally use tuples for heterogeneous (different) data types and lists for homogeneous (similar) data types.
Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance boost.
Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
Python Sets
In this tutorial, you'll learn everything about Python sets; how they are created, adding or removing elements from them, and all operations performed on sets in Python.
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function.
It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.
# Different types of sets in Python# set of integersmy_set ={1,2,3}print(my_set)# set of mixed datatypesmy_set ={1.0,"Hello", (1,2,3)}print(my_set)
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
Try the following examples as well.
# set cannot have duplicates# Output: {1, 2, 3, 4}my_set ={1,2,3,4,3,2}print(my_set)# we can make set from a list# Output: {1, 2, 3}my_set =set([1, 2, 3, 2])print(my_set)# set cannot have mutable items# here [3, 4] is a mutable list# this will cause an error.my_set ={1,2, [3,4]}
Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we use the set() function without any argument.
# Distinguish set and dictionary while creating empty set# initialize a with {}a ={}# check data type of aprint(type(a))# initialize a with set()a =set()# check data type of aprint(type(a))
<class 'dict'>
<class 'set'>
Modifying a set in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does not support it.
We can add a single element using the add() method, and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
# initialize my_setmy_set ={1,3}print(my_set)# my_set[0]# if you uncomment the above line# you will get an error# TypeError: 'set' object does not support indexing# add an element# Output: {1, 2, 3}my_set.add(2)print(my_set)# add multiple elements# Output: {1, 2, 3, 4}my_set.update([2, 3, 4])print(my_set)# add list and set# Output: {1, 2, 3, 4, 5, 6, 8}my_set.update([4, 5], {1, 6, 8})print(my_set)
A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if the element is not present in the set. On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set).
The following example will illustrate this.
# Difference between discard() and remove()# initialize my_setmy_set ={1,3,4,5,6}print(my_set)# discard an element# Output: {1, 3, 5, 6}my_set.discard(4)print(my_set)# remove an element# Output: {1, 3, 5}my_set.remove(6)print(my_set)# discard an element# not present in my_set# Output: {1, 3, 5}my_set.discard(2)print(my_set)# remove an element# not present in my_set# you will get an error.# Output: KeyErrormy_set.remove(2)
Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary.
We can also remove all the items from a set using the clear() method.
# initialize my_set# Output: set of unique elementsmy_set =set("HelloWorld")print(my_set)# pop an element# Output: random elementprint(my_set.pop())# pop another elementmy_set.pop()print(my_set)# clear my_set# Output: set()my_set.clear()print(my_set)print(my_set)
Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A ={1,2,3,4,5}>>> B ={4,5,6,7,8}
Set Union
Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the union() method.
# Set union method# initialize A and BA ={1,2,3,4,5}B ={4,5,6,7,8}# use | operator# Output: {1, 2, 3, 4, 5, 6, 7, 8}print(A | B)
{1, 2, 3, 4, 5, 6, 7, 8}
Try the following examples on Python shell.
# use union function>>> A.union(B){1,2,3,4,5,6,7,8}# use union function on B>>> B.union(A){1,2,3,4,5,6,7,8}
Set Intersection
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the intersection() method.
# Intersection of sets# initialize A and BA ={1,2,3,4,5}B ={4,5,6,7,8}# use & operator# Output: {4, 5}print(A & B)
{4, 5}
Try the following examples on Python shell.
# use intersection function on A>>> A.intersection(B){4,5}# use intersection function on B>>> B.intersection(A){4,5}
Set Difference
Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using the difference() method
# Difference of two sets# initialize A and BA ={1,2,3,4,5}B ={4,5,6,7,8}# use - operator on A# Output: {1, 2, 3}print(A - B)
{1, 2, 3}
Try the following examples on Python shell
# use difference function on A>>> A.difference(B){1,2,3}# use - operator on B>>> B - A{8,6,7}# use difference function on B>>> B.difference(A){8,6,7}
Set Symmetric Difference
Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference() .
# Symmetric difference of two sets# initialize A and BA ={1,2,3,4,5}B ={4,5,6,7,8}# use ^ operator# Output: {1, 2, 3, 6, 7, 8}print(A ^ B)
{1, 2, 3, 6, 7, 8}
Try the following examples on Python shell.
# use symmetric_difference function on A>>> A.symmetric_difference(B){1,2,3,6,7,8}# use symmetric_difference function on B>>> B.symmetric_difference(A){1,2,3,6,7,8}
Other Python Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:
Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the in keyword
# in keyword in a set# initialize my_setmy_set =set("apple")# check if 'a' is present# Output: Trueprint('a'in my_set)# check if 'p' is present# Output: Falseprint('p'notin my_set)
True
False
Iterating Through a Set
We can iterate through each item in a set using a for loop.
>>>for letter inset("apple"):... print(letter)... apel
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with sets to perform different tasks.
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable, it does not have methods that add or remove elements.
# Frozensets# initialize A and BA =frozenset([1, 2, 3, 4])B =frozenset([3, 4, 5, 6])
Try these examples on Python shell.
>>> A.isdisjoint(B)False>>> A.difference(B)frozenset({1, 2})>>> A | Bfrozenset({1, 2, 3, 4, 5, 6})>>> A.add(3)...AttributeError:'frozenset'object has no attribute 'add'
Dictionary in Python
In this tutorial, you'll learn everything about Python dictionaries; how they are created, accessing, adding, removing elements from them and various built-in methods.
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
An item has a key and a corresponding value that is expressed as a pair ( key: value ).
While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique
# empty dictionarymy_dict ={}# dictionary with integer keysmy_dict ={1:'apple',2:'ball'}# dictionary with mixed keysmy_dict ={'name':'John',1: [2,4,3]}# using dict()my_dict =dict({1:'apple', 2:'ball'})# from sequence having each item as a pairmy_dict =dict([(1,'apple'), (2,'ball')])
As you can see from above, we can also create a dictionary using the built-in dict() function.
Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys . Keys can be used either inside square brackets [] or with the get() method.
If we use the square brackets [] , KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.
# get vs [] for retrieving elementsmy_dict ={'name':'Jack','age':26}# Output: Jackprint(my_dict['name'])# Output: 26print(my_dict.get('age'))# Trying to access keys which doesn't exist throws error# Output Noneprint(my_dict.get('address'))# KeyErrorprint(my_dict['address'])
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not present, a new ( key: value ) pair is added to the dictionary.
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value .
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# Removing elements from a dictionary# create a dictionarysquares ={1:1,2:4,3:9,4:16,5:25}# remove a particular item, returns its value# Output: 16print(squares.pop(4))# Output: {1: 1, 2: 4, 3: 9, 5: 25}print(squares)# remove an arbitrary item, return (key,value)# Output: (5, 25)print(squares.popitem())# Output: {1: 1, 2: 4, 3: 9}print(squares)# remove all itemssquares.clear()# Output: {}print(squares)# delete the dictionary itselfdel squares# Throws Errorprint(squares)
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined
Python Dictionary Methods
Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.
Here are a few example use cases of these methods.
We can test if a key is in a dictionary or not using the keyword in. Notice that the membership test is only for the keys and not for the values.
# Membership Test for Dictionary Keyssquares ={1:1,3:9,5:25,7:49,9:81}# Output: Trueprint(1in squares)# Output: Trueprint(2notin squares)# membership tests for key only not value# Output: Falseprint(49in squares)
True
True
False
Iterating Through a Dictionary
We can iterate through each key in a dictionary using a for loop.
# Iterating through a Dictionarysquares ={1:1,3:9,5:25,7:49,9:81}for i in squares:print(squares[i])
1
9
25
49
81
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.
Here are some examples that use built-in functions to work with a dictionary.