Table of Contents
List
List operations
Example
Output
Use index to access list elements
Iterate over the list
Use For Loop
Repeat operator (*) on list items
Tuples in Python
Tuple slice
Use index to access tuple elements
EXAMPLE
Dictionary in Python
in conclusion
Home Backend Development Python Tutorial What are composite data types and data structures in Python?

What are composite data types and data structures in Python?

Aug 19, 2023 pm 04:45 PM
python data structure Composite data type

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”]
Copy after login

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)
Copy after login

Output

('Size of a List = ', 5)
Copy after login

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])
Copy after login

Output

('Element at index 2:', 8)
('last element of an input list:', 2)
Copy after login

Notice

When we try to use an index that does not exist or is too large, an IndexError

will be thrown

Iterate 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)
Copy after login

Output

Input list elements:
10
20
30
40
50
Copy after login

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)
Copy after login

Output

[5, 6, 7, 5, 6, 7]
Copy after login

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]
Copy after login
The Chinese translation of

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])
Copy after login

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)
Copy after login

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])
Copy after login

Output

('Element at index 2:', 8)
('last element of an input tuple:', 2)
Copy after login

Notice

When we try to use an index that does not exist or is too large, an IndexError

will be thrown

Dictionary 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 of

Example

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()))
Copy after login

Output

[10, 12, 14]
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

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 and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

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 vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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 vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

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.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

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.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

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".

See all articles