Master Python Lists: Create, Access, and Slice Elements with Easy Examples
This article introduces Python lists, explains how they differ from arrays, shows two creation methods using brackets and the list() function, and demonstrates element access via indexing and slicing with clear code examples and output screenshots.
1. Introduction
In Python programming, lists are frequently used. For example, to store the total scores of 50 students, using a list is far more convenient than defining 50 separate variables.
2. Getting to Know Lists
Unlike C or Java, which have arrays, Python provides lists. A list stores elements inside square brackets [] separated by commas, e.g.:
listName = [element1, element2, element3, ... elementN]Lists can hold elements of the same type or different types, unlike C arrays which require the same type. Example:
listName = [1, 'a']3. Creating Lists
There are two ways to create a list:
1) Using square brackets:
listName = [element1, element2, element3, ... elementN]Example:
a = [1, 2, 3, 4, 5]
b = ["Python", "Java", "C语言"]2) Using the list() function to convert a tuple or string into a list: listName = list(a) Example:
a = ('Java', 10, 'Python', 'PHP', 20)
list1 = list(a)
print("list1列表中元素有: ", list1)
b = "This is Python"
list2 = list(b)
print("list2列表中元素有: ", list2)Resulting output:
4. Accessing List Elements
Two methods are available:
1) Indexing by position (starting at 0):
listName = ['A', 'B', 'C', 'D'] # define a list
element = listName[i] # access element at index i2) Slicing:
listName = ['A', 'B', 'C', 'D']
sublist = listName[start:end:step] # start, end, stepExample demonstrating various slices:
listName = ['A','B','C','D','E','F','G']
print(listName[1:3]) # ['B', 'C']
print(listName[3:]) # ['D','E','F','G']
print(listName[1:6:2]) # ['B','D','F']
print(listName[-5:-2]) # ['C','D','E']Output:
5. Summary
This article introduced what a Python list is and how to create and access its elements. It covered list creation using brackets and the list() function, and demonstrated element access via indexing and slicing with practical code examples.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
