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

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 −

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.

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

Few more examples —

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

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 −

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.

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.

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 −

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.

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 −

Negative Indexing

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

Update and Delete List Items

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

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

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

The remove() method removes the specified item:

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

The del keyword removes the specified index:

The del keyword can also delete the list completely:

The clear() method empties the list:

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:

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

Join Two Lists

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

Join two list:

Append list2 into list1:

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

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.

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.

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 −

Negative Indexing

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

Add Items

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

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.

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:

Join Two Tuples

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

Python Sets

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

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.

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

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.

Remove Item

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

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

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

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

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

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:

The del keyword will delete the set completely:

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:

The update() method inserts the items in set2 into 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:

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

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

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

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 −

Removing Items

There are several methods to remove items from a dictionary:

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

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

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

The del keyword can also delete the dictionary completely:

The clear() keyword empties the dictionary:

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:

Another way to make a copy is to use the built-in method 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.

Entrepreneur | Business Enhancer | Developer