Just Python Part 4— Strings and Collections (Lists, Sets, Dictionaries, Tuples)

Harman Bhatia
Feb 4 · 11 min read

Python Strings

String type is created in python are surrounded by single quotation mark or double quotation mark. Strings can be displayed with the Print() function and can be assigned to the variables. For example −

'Hello World!' #Creating the string 
var1 = "Python Programming" #Assigning the string to variable.
print("Hello World!") #Output - Hello World!
print(var1) #Output - Python Programming

Slicing and Indexing

You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.

var1 = "Python Programming" print(var1[2:6]) #Output - 'thon'

Here the index starts from 0, now 2nd position is at ‘t’ and 6th position is exclusive so output is ‘thon’.

Few more examples —

var1 = "Python Programming"print(var1[0]) #Output - 'P' print(var1[0:6]) #Output - 'Python'print(var1[:4]) #Output - 'Pyth'print(var1[7:]) #Output - 'Programming'print("Updated String :- ", var1[:6] + 'Strings')  #Output - 'Python Strings'

To get the length of a string, use the len() function.

var1 = "Python"print(len(var1)) #Output: 6

String Methods

Python has a set of built-in methods that you can use on strings.

Assume string variable x holds “Hello, Python!”

All string methods returns new values. They do not change the original string.

There are various other methods such as min(), max(), count(), center(), join() etc. If you wish to go through each method, please go to the link mentioned at the end of the tutorial.

String Special Operator

Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then −

String Format Operator

One of Python’s coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C’s printf() family. Following is a simple example −

print("My name is %s and weight is %d kg!" % ('Alexa', 47))Output - My name is Alexa and weight 47 kg

Here is the list of complete set of symbols which can be used along with % −

Also, We can use the format() method to combine strings and numbers.

weight = 47x = "My name is {} and weight is {} kg!"print(x.format('Alexa', weight))Output - My name is Alexa and weight 47 kg

Escape Character

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

x = “We are the so-called \”Vikings\” from the north.”print(x)  Output - We are the so-called ”Vikings” from the north.

Python Collections

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

List

A list is a collection which is ordered and changeable. Creating a list is as simple as putting different comma-separated values between square brackets. For example −

list1 = ['computer', 'laptop', 101, 2901]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

Remember that the first item has index 0.

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

To get the length of a list, use the len() function.

var1 = ['computer', 'laptop', 101, 2901]print(len(var1)) #Output: 4

Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

list1 = ['computer', 'laptop', 101, 2901];
list2 = [1, 2, 3, 4, 5 ];
print("First element of list 1 is ", list1[0])
print("Slicing list 2 from 1 to 4 - ", list2[1:4])
First element of list 1 is computer
Slicing list 2 from 1 to 4: [2, 3, 4]

Negative Indexing

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

thislist = ["apple", "banana", "cherry"]
print(thislist[-1]) # Output - "cherry"
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1]) #Output - ['orange', 'kiwi', 'melon']

Update and Delete List Items

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

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) #Output - ["apple", "banana", "cherry","orange"]

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

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist) #Output - ["apple", "orange", "banana", "cherry"]

To change the value of a specific item, refer to the index number:

thislist = [“apple”, “banana”, “cherry”]
thislist[1] = “orange”
print(thislist) #Output - ["apple", "orange", "cherry"]

The remove() method removes the specified item:

thislist = [“apple”, “banana”, “cherry”]
thislist.remove(“banana”)
print(thislist) #Output - ["apple", "cherry"]

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

thislist = [“apple”, “banana”, “cherry”]
thislist.pop()
print(thislist) #Output - ["apple", "banana"]

The del keyword removes the specified index:

thislist = [“apple”, “banana”, “cherry”]
del thislist[0]
print(thislist) #Output - [“banana”, “cherry”]

The del keyword can also delete the list completely:

thislist = ["apple", "banana", "cherry"]
del thislist
print(thislist) #this will cause an error because you have succsesfully deleted "thislist".

The clear() method empties the list:

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

Copy a List

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().

Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist) #["apple", "banana", "cherry"]

Another way to make a copy is to use the built-in method list().

thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist) #["apple", "banana", "cherry"]

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.

Join two list:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3) # Output - ['a', 'b', 'c', 1, 2, 3]

Append list2 into list1:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1) # Output - ['a', 'b', 'c', 1, 2, 3]

Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1) # Output - ['a', 'b', 'c', 1, 2, 3]

List Methods

Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

tup1 = ('computer', 'laptop', 101, 2901)
tup2 = (1, 2, 3, 4, 5 )
tup3 = ("a", "b", "c", "d")

Remember that the first item has index 0.

Similar to list indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.

To get the length of a tuple, use the len() function.

var1 = ('computer', 'laptop', 101, 2901)print(len(var1)) #Output: 4

Accessing Values in Tuples

To access values in tuples, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

tup1 = ('computer', 'laptop', 101, 2901)
tup2 = (1, 2, 3, 4, 5)
print("First element of tup1 is ", tup1[0])
print("Slicing tup2 from 1 to 4 - ", tup2[1:4])
First element of tup1 is computer
Slicing tup2 from 1 to 4: (2, 3, 4)

Negative Indexing

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

tup1 = ("apple", "banana", "cherry")
print(tup1[-1]) # Output - "cherry"
tup2= ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(tup2[-4:-1]) #Output - ('orange', 'kiwi', 'melon')

Add Items

Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)

Create Tuple With One Item

To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.

thistuple = ("apple",)
print(type(thistuple)) #type tuple

#NOT a tuple
thistuple = ("apple")
print(type(thistuple)) # type str

Remove Items

Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:

The del keyword can delete the tuple completely:

thistuple = (“apple”, “banana”, “cherry”)
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Join Two Tuples

To join two or more tuples you can use the + operator:

tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2
print(tuple3) # Output - ('a', 'b', 'c', 1, 2, 3)

Python Sets

A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.

thisset = {"apple", "banana", "cherry"}
print(thisset) # {'cherry', 'apple', 'banana'}

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Access Items

You cannot access items in a set by referring to an index, since sets are unordered the items has no index.

But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x) # prints each element
thisset = {"apple", "banana", "cherry"}

print("banana" in thisset) # True

To determine how many items a set has, use the len() method:

var1 = {'computer', 'laptop', 101, 2901}print(len(var1)) #Output: 4

Change Items

Once a set is created, you cannot change its items, but you can add new items.

Add Items

To add one item to a set use the add() method.

To add more than one item to a set use the update() method.

set1= {"apple", "banana", "cherry"}

set1.add("orange")

print(set1) #{"apple", "orange", "banana", "cherry"}
set1.update(["orange", "mango"])

print(set1) #{"apple", "orange", "banana","mango", "cherry"}

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

rm_set = {"apple", "banana", "cherry"}

rm_set.remove("banana")

print(rm_set) # Output: {"apple", "cherry"}

Note: If the item to remove does not exist, remove() will raise an error.

Remove “banana” by using the discard() method:

rm_set = {"apple", "banana", "cherry"}

rm_set.discard("banana")

print(rm_set) # Output: {"apple", "cherry"}

Note: If the item to remove does not exist, discard() will NOT raise an error.

Remove the last item by using the pop() method:

rm_set = {"apple", "banana", "cherry"}

x = rm_set.pop()

print(x) # Output: apple

print(rm_set) #Output: {'cherry', 'banana'}

Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.

The clear() method empties the set:

rm_set = {"apple", "banana", "cherry"}

rm_set.clear()

print(rm_set) #set()

The del keyword will delete the set completely:

rm_set = {"apple", "banana", "cherry"}

del rm_set

print(rm_set) #this will raise an error because the set no longer exists

Join Two Sets

There are several ways to join two or more sets in Python.

You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:

The union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

The update() method inserts the items in set2 into set1:

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set1.update(set2)
print(set1)

Note: Both union() and update() will exclude any duplicate items.

Set Methods

Python has a set of built-in methods that you can use on sets.

Python Dictionaries

A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.

Create and print a dictionary:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict) #This will print the dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict['Age']) #Output: 7
print(dict['Name']) #Output: Zara

There is also a method called get() that will give you the same result:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict.get('Age')) #Output: 7

To determine how many items (key-value pairs) a dictionary has, use the len() method.

print(len(thisdict))

Updating Dictionary

You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print(dict['Age']) #Output: 8
print(dict['School']) #Output: DPS School

Removing Items

There are several methods to remove items from a dictionary:

The pop() method removes the item with the specified key name:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict.pop('Class')
print(dict) #Output: {'Name': 'Zara', 'Age': 7}

The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict.popitem()
print(dict) #Output: {'Name': 'Zara', 'Age': 7}

The del keyword removes the item with the specified key name:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Class']
print(dict) #Output: {'Name': 'Zara', 'Age': 7}

The del keyword can also delete the dictionary completely:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict
print(dict) #this will cause an error because "dict" no longer exists.

The clear() keyword empties the dictionary:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict.clear()
print(dict)

Copy a Dictionary

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

Make a copy of a dictionary with the copy() method:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
cdict = dict.copy()
print(cdict) # It will be the copy of dict

Another way to make a copy is to use the built-in method dict().

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
cdict = dict(dict)
print(cdict) # It will be the copy of dict

Dictionary Methods

So this is all about the Strings and Collections i.e. Lists, Tuples, Sets and Dictionaries in python. Below are few links which will be helpful to you.

Nothing works until you work so practice more, solve as many different types of problems as you can. Next we will be moving to the Python Loops and Conditions.

    Harman Bhatia

    Written by

    Entrepreneur | Business Enhancer | Developer

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade