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]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])
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!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
