


What are composite data types and data structures in Python?
In this article, we will explain composite data types and data structures in Python.
So far, variables can only store one value. What if we want to save many related values?
We can simply create different variables for each variable.
But what if we don’t know how many values there will be?
What if we want to use these values in a loop?
Composite data structure is a data type that can store a large number of values.
In Python, there are various types of composite data structures.
We will focus mainly on the list.
Finally, we’ll take a quick look at Sets, Tuples, and Dictionaries.
List
In Python, a list is an ordered sequence that can hold multiple object types, such as integers, characters, or floating point numbers. In other programming languages, lists are equivalent to arrays.
A list is simply a list of values separated by commas and enclosed in square brackets [].
inputList = [“hello”, “tutorialspoint”, 1, 3.5, “python”]
List operations
There are many operations that can be performed on lists in order to create expressions from them.
1) Use the len() function to get the size of the list
Use len() function Get the length/size of the list (len() method returns the number of items in the object. When the object is a list, the len() function returns the number of items in the list), and create a variable to store it.
Example
# input list lst = ["Hello", "TutorialsPoint", 78, "Hi", "Everyone"] # getting list length listLength = len(lst) # Printing the size of a list print("Size of a List = ", listLength)
Output
('Size of a List = ', 5)
Use index to access list elements
The term "indexing" refers to getting an element based on its position in an iterable object.
Indices start from 0. The first element in the sequence is represented by index 0.
Negative indexes start from -1. The last element in the sequence is represented by index -1.
Example
# input list inputList =[1, 4, 8, 6, 2] # accessing the list element at index 2 using positive indexing print("Element at index 2:", inputList[2]) # accessing the last element in list using negative indexing print("last element of an input list:", inputList[-1])
Output
('Element at index 2:', 8) ('last element of an input list:', 2)
Notice
When we try to use an index that does not exist or is too large, an IndexError
will be thrownIterate over the list
Use For Loop
The following program uses a for loop to print all list elements:
# input list inputList = [10, 20, 30, 40, 50] print("Input list elements:") # traversing through all elements of the list using for loop for element in inputList: # printing each element of the list print(element)
Output
Input list elements: 10 20 30 40 50
Repeat operator (*) on list items
Python List also includes the * operator, which allows you to create a new list in which elements are repeated a specified number of times.
Example
The following program uses the * operator to repeat a list a given number of times -
# input list inputList = [5, 6, 7] # Repeating the input list 2 times using the * operator print(inputList * 2)
Output
[5, 6, 7, 5, 6, 7]
Here we are multiplying the list of random values twice using * operator so that the output is the given list repeated twice.
Tuples in Python
Tuple is an immutable sequence data type that can contain elements of different data types. A tuple is simply a collection of Python objects separated by commas. Since tuples are static, they are faster than lists.
The syntax of lists and tuples is somewhat different. Lists are represented by square brackets [], while tuples are represented by brackets ().
Tuple slice
We can use tuple slicing. It's similar to how we use strings and lists. Tuple slices are used to get various items. We also use the slicing operator to perform tuple slicing. The slicing operator can be expressed with the following syntax
[start:stop:step]
Example
is:Example
# Input tuple givenTuple = ("Welcome", "this", "is", "TutorialsPoint", "Website", 10) # Slicing with start and stop values(indices) print('Tuple slicing from index 1 to index 6 :', givenTuple[1:6]) # Slicing with only stop values(indices) print("Tuple slicing till index 7: ", givenTuple[:7])
Output
Tuple slicing from index 1 to index 6 : ('this', 'is', 'TutorialsPoint', 'Website', 10) Tuple slicing till index 7: ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)
Use index to access tuple elements
Like lists, tuples also use indexes to access their elements. The only difference is that tuples are immutable (cannot be changed), while lists are mutable. The Chinese translation of
EXAMPLE
is:EXAMPLE
# input tuple inputTuple = (1, 4, 8, 6, 2) # accessing the tuple element at index 2 using positive indexing print("Element at index 2:", inputTuple[2]) # accessing the last element in tuple using negative indexing print("last element of an input tuple:", inputTuple[-1])
Output
('Element at index 2:', 8) ('last element of an input tuple:', 2)
Notice
When we try to use an index that does not exist or is too large, an IndexError
will be thrownDictionary in Python
Use the dict.keys() method to get a list of all keys from the dictionary
Apply it to the input dictionary using the keys() function, then convert the result to a list using the list() function (which converts a sequence/iterable to a list) , to print all keys of the dictionary.
The Chinese translation ofExample
is:Example
# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} # Printing the list of keys of a dictionary using the keys() function # list() methods convert an iterable into a list print(list(demoDictionary.keys()))
Output
[10, 12, 14]
in conclusion
In this article, we learned about composite data types and data structures, along with some examples of them.
The above is the detailed content of What are composite data types and data structures in Python?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
