Strings, Lists, Dictionaries, Tuples, and Sets (Quick Code-Python)

Shreedhar Vellayaraj
Geek Culture
Published in
9 min readSep 4, 2021
Credit: Unsplash.com

In this third chapter of the Quick Code-Python series, we are going to understand various key data structures that are available in python, along with some practical code snippets that are essential during coding that you would encounter on a daily basis.

Note: I’ve written the Quick Code-Python series in a linear fashion so that even a newbie can follow along the series to get a grasp of what python can actually do. For folks that are good with the fundamentals, you can follow along with the series to refresh your concepts or choose any of the chapters in the series that you want to know more about.

I’ve added the Format and User Input operation as a part of this blog since some wouldn’t be familiar with getting input from the user and using the .format() method to call the variables.

  1. Format and User Input Operation
  2. Strings and Booleans
  3. Lists
  4. Dictionaries
  5. Tuples and Sets

Let’s begin.

1. Format and User Input Operation

Format

Before understanding the User Input operation we need to understanding writing print statements using .format() method(a method is just a function that belongs to an object).

x = 34
y = 55
Z = x*y
M = x/y
print('Multiplication = {}, Division = {}'.format(Z,M))
O/P:
Multiplication = 1870, Division = 0.6181818181818182

Now, there’s another way of using the format method.

X = 34
Y = 55
print('Multiplication = {}, Division = {}'.format(X*Y,X/Y))O/P:
Multiplication = 1870, Division = 0.6181818181818182

We get the same output. The second one’s more efficient, but when you have more operations to do, it is better to assign variables and print them like the first method.

User Input

We need to prompt the user to enter the values of a particular variable, which will be used for the execution of the program. Now, let’s get input from the user using the Input operation in python.

To get user input, all we need to do is type input()

a = int(input("Enter a number: ")) 
b = int(input("Enter another number: "))
print('Multiplication = {}, addition = {}'.format(a*b, a+b))O/P:
Enter a number: 5
Enter another number: 6
Multiplication = 30, addition = 11

Note that you(the code asks you to enter)are entering the numbers 5 and 6 and it’s not some default value.

Printing the square and cube of a number

x = int(input("Enter a number: "))#converting x into an integerprint('The square and cube of {} is {} and {}'.format(x, x*x, x*x*x))O/P: 
Enter a number: 6
The square and cube of 6 is 36 and 216

Python accepts all inputs as strings which becomes a barrier when we need to do arithmetic operations on numbers taken from the user input. That’s the reason we’ve put int()in Line 1, we need to convert the string to an integer.

Converting kmph into mph

kmh = int(input("Enter speed in km/h: "))
mph = 0.6214 * kmh
print("Speed in Km per hour = ", kmh, "KM/H")
print("Speed in Miles per hour = ", mph, "MPH")
O/P:
Enter speed in km/h: 100
Speed in Km per hour = 100 KM/H
Speed in Miles per hour = 62.13999999999999 MPH

Calculating the area and perimeter of a rectangle

width = int(input("Enter Width: "))
length = int(input("Enter Length: "))
area = width * length
perimeter = 2 * (width + length)
print('Area = {}, Perimeter = {}'.format(area, perimeter))O/P:
Enter Width: 3
Enter Length: 4
Area = 12, Perimeter = 14

2. Strings and Boolean

A String in python is just a sequence of characters. You can do various manipulations on python using the methods available in strings.

name = "shreedhar"
print(name)
z = type(name)
print(z)
O/P:
shreedhar
<class 'str'>

Remember I told you that python stores all the user input as a string by default and even if you add two numbers without converting them to an integer, it would just add them as two strings and not numbers.

a = input('enter first number: ')
b = input('enter second number: ')
print('the answer is : {}'.format(a+b))
O/P:
enter first number: 4
enter second number: 5
the answer is : 45
credit: Reddit(programming humor)

Code from the meme (above)

'python goes b' + 'r'*10O/P:
'python goes brrrrrrrrrr'

Let’s add two strings to print my Twitter username

first_name = "@shreedhar" 
last_name = "v16"
username = first_name + "_" + last_name
print("My twitter username is : ",username)
O/P:
My twitter username is : @shreedhar_v16

There are many methods that we can apply to our string function to do various manipulations.

#converting a string to uppercase
y = 'shreedharv16'
z = y.upper()
z
O/P:
'SHREEDHARV16'
#splitting our string
y = 'shreedhar_v16'
z = y.split('_')
z
O/P:
['shreedhar', 'v16']

We can also get a particular string from the list available from the output. The memory location of the first character in a string starts with 0.

Credit: Real Python

String slicing and manipulation

#splitting our string
y = 'shreedhar_v16'
z = y.split('_')
z
O/P:
['shreedhar', 'v16']
#taking the 1st and 2nd element
print(z[0])
print(z[1])
O/P:
'shreedhar'
'v16'

Booleans are just values that return either True or False. When you code some high-level python codes you can use them just as flags.

x = 10
y = 20
print(x>y)
print(x<y)
print(x==y)
print(x!=y)
O/P:
False
True
False
True

Code to display username, password and to check if the user is active or not.

Note: \n is used to specify a new line on our print statement

name = "@shreedharv16"
password = '********'
active_user = True
print('Username: {} \nPassword : {} \nActive User: {} \n'.format(name,password,active_user))O/P:
Username: @shreedharv16
Password : ********
Active User: True

Code to strip the name from the mail address

inp_str = input("Enter your e-mail address:")
out_str = inp_str.split('@')
print('The name from the mail id is ',out_str[0])
O/P:
Enter your e-mail address:shreedharv1234@gmail.com
The name from the mail id is shreedharv1234

Code to count the number of letters in your name from the mail address

inp_str = input("Enter your e-mail address:")
out_str = inp_str.split('@')
print('There are {} characters in your username'.format(len(out_str[0])))O/P:
Enter your e-mail address:shreedharv16@gmail.com
There are 12 characters in your username

3. Lists

A list is an ordered collection of elements. A list is mutable which means that it allows duplicate members within the list.

Let’s create our first list

my_first_list = [1, 2, 3]
my_first_list
O/P:
[1, 2, 3]
#creating a nested list
my_list = ["shreedhar", [3, 3, 3]]
my_list
O/P:
['shreedhar', [3, 3, 3]]

Duplicate elements have successfully been printed in the second example

Accessing elements in our list and nested list(a list within a list)

names = ['shreedhar', 'joe', 'aj']
print(names[0])
print(names[1])
print(names[2])
O/P:
shreedhar
joe
aj
list_of_contents = ['01',['23','IA'],'ef']
print("second element in the second list is : ",list_of_contents[1][1])
O/P:
second element in the second list is : IA

We need to understand what slicing an index is.

list[:] print all the elements in the list

list[2:4]print elements from the location [2] and [3]. note that the upper limit [4] is reduced by 1. Always (n-1) for upper limit values in the list.

list[2:5]prints the elements from [2] to [4]

list[:2] prints the last 2 elements in the list

list[2:] prints elements from the second location in the list

list[:-1] prints the last element in the list

names = ['sara', 'john', 'aj','dimple','kv']
print(names[:2])
print(names[2:4])
print(names[2:5])
print(names[:])
print(names[2:])
O/P:
['sara', 'john']
['aj', 'dimple']
['aj', 'dimple', 'kv']
['sara', 'john', 'aj', 'dimple', 'kv']
['aj', 'dimple', 'kv']

Let’s look at other methods available on the list

#add a new element
names = ['sara', 'john', 'aj','dimple','kv']
names.append('zoe')
print(names)
O/P:
['sara', 'john', 'aj', 'dimple', 'kv', 'zoe']
#remove john from the list
names = ['sara', 'john', 'aj','dimple','kv']
names.remove('john')
print(names)
#delete using the index number
del names[0]
pirnt(names)
O/P:
['sara', 'aj', 'dimple', 'kv', 'zoe']
['aj', 'dimple', 'kv', 'zoe']

If you’ve ever used any other programming languages, besides python you’ll know that even basic operations such as sorting or reversing a list can take a lot of lines of code to run it.

Credit: Reddit(progrmaminghumor)

But python takes just a couple of lines to do the task

#sort a list
my_list = [50, 20, 30, 10, 40, 15, 45]
my_list.sort()
print(my_list)
O/P:
[10, 15, 20, 30, 40, 45, 50]
#reverse a list
my_list.reverse()
print(my_list)
O/P:
[50, 45, 40, 30, 20, 15, 10]

Create a new friends list from your original friend's list that only has the last names of each group

friends_list = [['joe','sam','tina'],['aj','kd','cody'],['trucker','carl','sussie']]#creating an empty friends list
friends_list2 = []
friends_list2.append(friends_list[0][-1])
friends_list2.append(friends_list[1][-1])
friends_list2.append(friends_list[2][-1])
friends_list2
O/P:
['tina', 'cody', 'sussie']

4. Dictionaries

Dictionaries are a key-value pair that is used to store data in the value that can be accessed with the key, just like how we access a list using index values.

The general format of a dictionary is,

dict = {'key1':'value1',
'key2':'value2',
'key3':'value3'}
dict
O/P:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
credit: benjamin dicken

Creating a dictionary for a watch product

#product dictionary
product = {"Name": "Watch",
"Color": "Blue",
"Brand": "Fossil"}
product
O/P:
{'Name': 'Watch', 'Color': 'Blue', 'Brand': 'Fossil'}
#adding year to the dict
product["Year"] = "1887"
print(product)
#deleting color key
del product["Color"]
print(product)
O/P:
{'Name': 'Watch', 'Color': 'Blue', 'Brand': 'Fossil', 'Year': '1887'}
{'Name': 'Watch', 'Brand': 'Fossil', 'Year': '1887'}

You can also check the keys and values of the dictionary from the .keys() and .values() method

#check the keys
product.keys()
O/P:
dict_keys(['Name', 'Brand', 'Year'])
#check the values
product.values()
O/P:
dict_values(['Watch', 'Fossil', '1887'])

Finding the average and the total marks in a class using a dictionary

mark_list = {"sam": 89,
"aj": 78,
"kd": 45,
"mk":90}
print('The total marks : ',sum(mark_list.values()))
print('The average mark : ',sum(mark_list.values())/4)
O/P:
The total marks : 302
The average mark : 75.5

5. Tuples and Sets

Tuple

A Tuple can be defined as immutable python objects that are sequences just like how a list is, except a list is mutable(modifiable) but a tuple is immutable(nonmodifiable). The only other difference is that a list uses ['list_name1'] whereas a tuple uses ('tuple_name1')

Creating our first tuple

my_tuple1 = ('sam',323,'joe',304,'hello',123)
my_tuple2 = (3,4,5,'karin')
print(my_tuple1)
print(my_tuple2)
O/P:
('sam', 323, 'joe', 304, 'hello', 123)
(3, 4, 5, 'karin')

Accessing a tuple is the same as accessing a list

print(my_tuple1[3])
print(my_tuple2[:-1])
print(my_tuple1[3:])
O/P:
304
(3, 4, 5)
(304, 'hello', 123)

Let’s try to assign some values to the tuples created

my_tuple1 = ('sam',323,'joe',304,'hello',123)
my_tuple1[2] = 33
O/P:
TypeError: 'tuple' object does not support item assignment

Since a tuple is immutable we can’t assign any new values for an existing tuple, that’s why we get a type error.

You can’t even delete the elements in a tuple

my_tuple = (430, 23, 22, [14, 44])
del my_tuple[3]
O/P:
TypeError: 'tuple' object doesn't support item deletion

But, don’t worry we can add values to a tuple using a list

names = ('shree','joe',23,[33,44])
names[3][0] = 25
print(names)
O/P:
('shree', 'joe', 23, [25, 44])

Set

A set can be defined as an unordered collection of items, that does not allow any duplicates to be present in them. We can create a set using {'value1'}

Creating our first set

my_set = {1, 2, 3}
print(my_set)
O/P:
{1,2,3}

Adding duplicates to a set and only removes the duplicates while storing and printing

my_set = {1,2,3,4,3,2}
print(my_set)
O/P:
{1, 2, 3, 4}

Applying a set to list removes the duplicates in a list and converts them into a set

my_list = [1,2,3,2]
my_set = set(my_list)
print(my_set)
O/P:
{1, 2, 3}

Adding your name to a set and converting the set to a list

names = {'john', 'karen','aj','sj'}
names.add('shree')
print(names)
O/P:
{'sj', 'shree', 'aj', 'karen', 'john'}
names_list = list(names)
print(names_list)
O/P:
['sj', 'shree', 'aj', 'karen', 'john']

That’s the end of the blog.

This image sums up all the topics that we’ve discussed. The main mistake that a beginner would do is change the type of parenthesis for different types. Don’t worry if you make the mistake, this could be solved with continuous practice.

credit: www.clcoding.com

Hope you’ve understood the various data structures explained. Just reading the blog isn’t enough. Run the code by copy-pasting on an IDE. Change the variables for yourselves and see how the output changes. Finally, try to write your own code.

Check out the previous chapter here of the Quick Code-Python series.

--

--