Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
data structures
community creator

Python data structures

Buchiredddypalli Koushik

In Python, we have four built-in data structures:

List

A data structure that stores an ordered collection of items in Python is called a list. List is generally represented within square brackets. List can have a number of elements and different data types.

l=[1,2,3,4,5,6]
print(l[0:7])

Methods

There are various methods supported by lists in Python:

Method Description
append() Adds an element to the end of the list.
copy() Returns a shallow copy of the list.
pop() Eliminates and returns an element from the list.
sort() Sorts all elements of a list in ascending order.
reverse() Reverses the order of all elements in the list.
remove() Eliminates an element from the list.

Tuple

Similar to a list, the tuple is a built-in data structure in Python. The most important difference between a list and tuple is mutability. Unlike lists, tuples are immutable, i.e., they can’t be modified. Tuple is defined with parentheses and each item is separated by commas. Tuples are used in scenarios where it is certain that the(set of) values belonging to some statement or a user-defined function will not change. Generally, a tuple is defined as follows:

t=(1,2,3,"Hello",3.14)
print(t)

Dictionary

A dictionary is an unordered, changeable, and indexed collection. Dictionary stores data in the form of key-value pairs, but the key defined for a dictionary needs to be unique. Dictionary is generally represented in the form of curly brackets with the key and value separated by a colon. The key-value pairs in a dictionary don’t follow any specific order.

d={"car":"Baleno",
   "model":"GT500",
   "year":2020
   }
print(d)
print("Specified key:",d['car'])

Same as lists, dictionaries have methods:

Method Description
items() Returns a new object of the dictionary’s items in (key,value) format.
keys() Returns a new object of the dictionary’s keys.
values() Returns a new object of the dictionary’s values.
copy() Returns a shallow copy of the dictionary.
clear() Removes all elements from the dictionary.
popitem() Removes and returns an arbitrary item (key,value).

Sets

A set is an is unordered and unindexed collection. In Python, sets are written with curly braces. In addition to being iterable and mutable, a set has no duplicate elements.

s={"Hello","World","this","is","python"}
print(s)

RELATED TAGS

python
data structures
community creator

CONTRIBUTOR

Buchiredddypalli Koushik
RELATED COURSES

View all Courses

Keep Exploring