Home
Posts
Article
Encyclopedia
Garden
Set
English

Understanding Collections in Python: Lists, Dictionaries, and Tuples

养花风水
26 Views
An extremely important term in programming languages is collections. In Python, collections are regarded as fundamental structures that allow programmers to bundle multiple items together. These multiple items can also be thought of as values. These collections—lists,tuples; dictionaries are the basic methods of structuring and processing data in python. Each collection type comes with different features and fulfills different roles, giving you the opportunity of selecting the most appropriate one for your needs. This article explains what collections in Python are, what the difference between them is, how they can be used, what their characteristics are (as well as their applications) with the help of examples, focusing on lists, dictionaries, and tuples.

What Are Collections in Python?

A collection is defined as an object or structure that contains a set of other objects. In programming, a collection is a container that contains multiple units. In Python, collections can be described as powerful instruments in programming that permit the user to store data in one variable, thus enabling the user to handle several data values at once. The role of collections in programming is crucial as it enables programmers to organize the data systematically for easy retrieval, modification, such as sorting, adding, deleting items in the collection, or changing the selected item.

Among the most used types of collections in Python include collections of lists, tuples, and dictionaries. Every collection has its own characteristics, features, benefits, and disadvantages depending on the area which you are using it in.

Lists: A Collection That Is Dynamic and Changeable

A list is one of the most frequently used types of collection in Python. It is a sequence which is a representation of a collection of items which is changeable and ordered. Being a sequence, Lists are flexible because elements in them can be added, removed, or changed. Possible elements of a list are numbers, strings, and other lists.

Lists are created by writing the items to be contained in it inside square brackets, `[]` separated by commas. Lists are indexed i.e., every item in a list is positioned (or indexed) such that the first item has an index of 0. You can access any item in a list by specifying the respective index of that item.

The list is carefully built which has one of the most fundamental attributes, which is, it's mutable. This means that elements of the list can be changed even though the list has already been built. You can put items in the list that were not there before, remove items that are in the list, or update items that are already in the list.

Here's an example of a list:

List Manipulation Example

  fruits = ['apple', 'banana', 'cherry']
fruits.append('orange') Adds 'orange' to the end of the list
fruits[1] = 'blueberry' Changes 'banana' to 'blueberry'
In this example, the `fruits` list was first said to contain 3 elements, however, it was changed through the addition of an item at the end and the modification of one of the factions `elements` lists.

Also, lists support slicing, i.e., you can select a subsection of elements contained within the list by using a start and end index point. For example ':' means all columns from index one through index three excluding index three, meaning that the selection will be made from the first element up to the second. This returns a sub list with all elements from index one through , but not including index three.

Tuples — Non-Changeable and Sequenced Objects

Another collection type in Python is tuples, this is very similar to a list except that there's one major difference – it is tuples which are extremely economic in structure. Once a tuple is created no further edits can be made: elements can neither be changed nor be added nor anything be removed. When a program is run, it can therefore make use of a collection of data without worrying of the data changing at any time during the program.

For creating a tuple you would simply require an opening bracket as opposed to a square bracket. They can still incorporate the same functionality as a list in that they are able to hold numerous items which can be of various types but when a tuple is created, that's it the contents cannot be changed.

A simple example of a tuple is shown below.

Tuple Example

  colors = ('red', 'green', 'blue') 
From this example it is easy to see that tuples, like lists, are ordered, meaning that the items in a tuple have a defined position or place in the tuple and can be retrieved by their index. However, in contrast with lists, once an element is assigned in a tuple such an element cannot be changed. If one tries to do so, an error occurs.

For example:

Tuple Immutability Example

  colors[1] = 'yellow'  This will cause an error since the tuples have been assigned and are thus immutable 
Although it has the disadvantage of being immutable, a construct of type tuple can be best suited for the work where it should be ensured that the data would not be changed by mistake. An illustrative example would be a fixed set of coordinates or an RGB representation of a color.

Also due to the fact that constant elements are present in tuples, they are usually faster and use less memory than lists. These are often employed in Python when there is a need to safeguard the data and when speed is important.

Dictionaries: Storing value against a unique key!

A specific type of structured data storage with the name of dictionary stores elements in the form of key-value relationships. In contrast to lists and tuples where elements/indexes are leveraged to reach an element, retrieval of values from a custom key to rather a value is possible in a dictionary. This characteristic of dictionaries renders them a suitable candidate to use in any situation where data has to be pulled based on a unique identifier, quickly.

A dictionary in python can be created by enclosing the key-value pairs in curly brackets, each pair being separated by a colon symbol. Key in regards to a particular value acts as a unique reference and each value represents data related to that specific key.

For instance consider a case of a simple python dictionary which describes attributes of a person:

Dictionary Example

  person = {'name': 'John', 'age': 30, 'city': 'New York'}
print(person['name']) Output will be 'John'
It is important to notice here that a dictionary type in python is an unordered collection, therefore its members or items are not arranged in a specific order like lists or tuples which hold data in an orderly manner. However, from version 3.7 onwards if the order of insertion of the items is maintained, only then the order of the items in the dictionary will be the same as their order of addition.

Providing fast lookup is one of the primary advantages of dictionaries. Knowing its key allows you to know its value almost instantly, which makes dictionaries suitable for use in areas requiring fast searching – for example a database or a data mapping.

You can change dictionaries also by inserting new elements or modifying the old ones:

Dictionary Modification Example

  person['age'] = 31  Sets the value of age to 31
person['job'] = 'Engineer' Sets the job for the person as a key-value pair
In addition, you can specify items to be removed from the dictionary: sectors can be deleted from the dictionary using `del` or using the `pop()` method:

Dictionary Deletion Example

  del person['city']   The key city and its value are removed 
0
0
Article
comment
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* Only support image type .JPG .JPEG .PNG .GIF
* Image can't small than 300*300px
Be the first comment
Just Reply
Elite Article
FeedBack

You have any problems or suggestions, please leave us a message.

Please enter content
Set
VIP
Sign out
Share

Share good articles, GFinger floral assistant witness your growth.

Please go to the computer terminal operation

Please go to the computer terminal operation

Forward
Insert topic
Remind friend
Post
/
Submit success Submit fail Picture's max size Success Oops! Something wrong~ Transmit successfully Report Forward Show More Article Help Time line Just Reply Let's chat! Expression Add Picture comment Only support image type .JPG .JPEG .PNG .GIF Image can't small than 300*300px At least one picture Please enter content