Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
The list of
There are four collection data types in Python:
- List: Is an ordered and mutable (modifiable) collection. Duplicate members are allowed.
- Tuple: A collection that is ordered and immutable or immutable. Duplicate members are allowed.
- Set: is an unordered, unindexed, and unmodifiable collection, but we can add new items to the collection. Duplicate members are not allowed.
- Dictionary: is an unordered, mutable (modifiable) and indexed collection. There are no duplicate members.
A list is an ordered and modifiable collection of different data types. Lists can be empty or have different data type items.
How to Create a list
In Python, we can create lists in two ways:
- Use list built-in functions
# grammar
lst = list(a)Copy the code
empty_list = list(a)# This is an empty list with no items in it
print ( len ( empty_list )) # 0
Copy the code
- Using square brackets, []
# grammar
lst = []
Copy the code
empty_list = [] # This is an empty list with no items in it
print ( len ( empty_list )) # 0
Copy the code
A list with initial values. We use len() to find the length of the list.
fruits = ['banana'.'orange'.'mango'.'lemon'] # Fruit list
vegetables = ['Tomato'.'Potato'.'Cabbage'.'Onion'.'Carrot'] # Vegetable list
animal_products = ['milk'.'meat'.'butter'.'yoghurt'] # List of animal products
web_techs = ['HTML'.'CSS'.'JS'.'React'.'Redux'.'Node'.'MongDB'] # Network technology
countries = ['Finland'.'Estonia'.'Denmark'.'Sweden'.'Norway']
Print the list and its length
print('Fruits:', fruits)
print('Number of fruits:'.len(fruits))
print('Vegetables:', vegetables)
print('Number of vegetables:'.len(vegetables))
print('Animal products:',animal_products)
print('Number of animal products:'.len(animal_products))
print('Web technologies:', web_techs)
print('Number of web technologies:'.len(web_techs))
print('Countries:', countries)
print('Number of countries:'.len(countries))
Copy the code
Output Fruits:'banana'.'orange'.'mango'.'lemon']
Number of fruits: 4
Vegetables: ['Tomato'.'Potato'.'Cabbage'.'Onion'.'Carrot']
Number of vegetables: 5
Animal products: ['milk'.'meat'.'butter'.'yoghurt']
Number of animal products: 4
Web technologies: ['HTML'.'CSS'.'JS'.'React'.'Redux'.'Node'.'MongDB']
Number of web technologies: 7
Countries: ['Finland'.'Estonia'.'Denmark'.'Sweden'.'Norway']
Number of countries: 5
Copy the code
- Lists can contain items of different data types
lst = [ 'Asabeneh' , 250 , True , { 'country' : 'Finland' , 'city' : 'Helsinki' }] # contains lists of different data types
Copy the code
Use positive indexes to access list items
We use their index to access each item in the list. A list index starts at 0. The figure below clearly shows where the index starts
fruits = ['banana'.'orange'.'mango'.'lemon']
first_fruit = fruits[0] We use its index to access the first item
print(first_fruit) # banana
second_fruit = fruits[1]
print(second_fruit) # the orange
last_fruit = fruits[3]
print(last_fruit) # lemon
# Last index
last_index = len(fruits) - 1
last_fruit = fruits[last_index]
Copy the code
Use negative indexes to access list items
A negative index means starting at the end, -1 means the last item, and -2 means the penultimate item.
fruits = ['banana'.'orange'.'mango'.'lemon']
first_fruit = fruits[-4]
last_fruit = fruits[-1]
second_last = fruits[-2]
print(first_fruit) # banana
print(last_fruit) # lemon
print(second_last) # mango.
Copy the code
Unpacking list items
lst = [ 'item' , 'item2' , 'item3' , 'item4' , 'item5' ]
first_item , second_item , third_item , * rest = lst
print ( first_item ) # item1
print ( second_item ) # item2
print ( third_item ) # item3
print( rest ) # ['item4', 'item5']
Copy the code
# First example
fruits = [ 'banana' , 'orange' , 'mango' , 'lemon' , 'lime' , 'apple' ]
first_fruit , second_fruit , third_fruit , * rest = lst
print ( first_fruit ) # banana
print ( second_fruit ) # orange
print ( third_fruit ) # mango.
print ( rest ) # ['lemon','lime','apple']
# second example of unpacking lists
first , second , third , * rest , tenth = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
print(first) # 1
print(second) # 2
print(third) # 3
print(rest) # [4,5,6,7,8,9]
print(tenth) # 10
The third example is about the unpacking list
countries = ['Germany'.'France'.'Belgium'.'Sweden'.'Denmark'.'Finland'.'Norway'.'Iceland'.'Estonia']
gr, fr, bg, sw, *scandic, es = countries
print(gr)
print(fr)
print(bg)
print(sw)
print(scandic)
print(es)
Copy the code
Slice items from the list
- Positive indexes: We can specify a series of positive indexes by specifying a start, end, and step, and the return value will be a new list. (Default start = 0, end = len(LST) -1 (last item), step = 1)
fruits = ['banana'.'orange'.'mango'.'lemon']
all_fruits = fruits[0:4] # It returns all fruit
# This will also give the same result as the one above
all_fruits = fruits[0:] # If we don't set where to stop it takes all the rest
orange_and_mango = fruits[1:3] The first index is not included
orange_mango_lemon = fruits[1:]
orange_and_lemon = fruits[::2] # here we use the third parameter, step. It will need every 2cnD item - ['banana', 'mango']
Copy the code
- Negative indexes: We can specify a series of negative indexes by specifying the start, end, and steps, and the return value will be a new list.
fruits = ['banana'.'orange'.'mango'.'lemon']
all_fruits = fruits[-4:] # It returns all fruit
orange_and_mango = fruits[-3: -1] # it does not include the last index,['orange', 'mango']
orange_mango_lemon = fruits[-3:] # this will give start from -3 to end,['orange', 'mango', 'lemon']
reverse_fruits = fruits[::-1] # A negative step takes the list in reverse order,['lemon', 'mango', 'orange', 'banana']
Copy the code
Modify the list
A list is an ordered collection of mutable or modifiable items. Let’s modify the fruit list.
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits[0] = 'avocado'
print(fruits) # ['avocado', 'orange', 'mango', 'lemon']
fruits[1] = 'apple'
print(fruits) # ['avocado', 'apple', 'mango', 'lemon']
last_index = len(fruits) - 1
fruits[last_index] = 'lime'
print(fruits) # ['avocado', 'apple', 'mango', 'lime']
Copy the code
Check the items in the list
Use the IN operator to check whether the item is a member of the list. See the example below.
fruits = ['banana'.'orange'.'mango'.'lemon']
does_exist = 'banana' in fruits
print(does_exist) #
does_exist = 'lime' in fruits
print(does_exist) # false
Copy the code
Add the item to the list
To add an item to the end of an existing list, we use the method append().
# grammar
lst = list ()
lst.append(item)
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits.append('apple')
print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple']
fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']
print(fruits)
Copy the code
Insert the item into the list
We can use the insert() method to insert a single item at the specified index in the list. Notice that other items move to the right. The plug-in () method takes two parameters: the index and the insert item.
# grammar
lst = [ 'item1' , 'item2' ]
lst.insert(index, item)
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits.insert(2.'apple') # Insert apple between orange and mango
print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon']
fruits.insert(3.'lime') # ['banana', 'orange', 'apple', 'lime', 'mango', 'lemon']
print(fruits)
Copy the code
Removes items from the list
The remove method removes the specified item from the list
# grammar
lst = [ 'item1' , 'item2' ]
lst.remove(item)
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon'.'banana']
fruits.remove('banana')
print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - this method removes the first occurrence of the item in the list
fruits.remove('lemon')
print(fruits) # ['orange', 'mango', 'banana']
Copy the code
Deletes the specified index, (or if the last item in the index is not specified), using the Pop () method to delete the item:
# grammar
lst = [ 'item1' , 'item2' ]
lst . pop () # Last term
lst.pop(index)
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits.pop()
print(fruits) # ['banana', 'orange', 'mango']
fruits.pop(0)
print(fruits) # ['orange', 'mango']
Copy the code
The title uses Del to delete the item
The delete key deletes the specified index and it can also be used to delete items within the index range. It can also remove lists entirely
# grammar
lst = [ 'item1' , 'item2' ]
del lst [ index ] # Only one project
del lst Delete the list completely
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon'.'kiwi'.'lime']
del fruits[0]
print(fruits) # ['orange', 'mango', 'lemon', 'kiwi', 'lime']
del fruits[1]
print(fruits) # ['orange', 'lemon', 'kiwi', 'lime']
del fruits[1:3] # # This will delete items between the given indexes, so it will not delete items with index 3!
print(fruits) # ['orange', 'lime']
del fruits
print(fruits) # This should give: NameError: the name "fruit" is not defined
Copy the code
Clear list items
Clear the list in the explicit () method:
# grammar
lst = [ 'item1' , 'item2' ]
lst.clear()
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits.clear()
print(fruits) # []
Copy the code
Copy the list
You can copy a list by reassigning it to a new variable: list2 = list1. Now, list2 is a reference to List1, and any changes we make in List2 will also modify the original list2, but in many cases we don’t like to modify the original version and prefer to have a different copy. One way to avoid these problems is to use copy().
# grammar
lst = [ 'item1' , 'item2' ]
lst_copy = lst . copy()
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits_copy = fruits.copy()
print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon']
Copy the code
Join the list
There are various ways to join or join two or more lists in Python.
- The plus operator (+)
# grammar
list3 = list1 + list2
Copy the code
positive_numbers = [1.2.3.4.5]
zero = [0]
negative_numbers = [-5, -4, -3, -2, -1]
integers = negative_numbers + zero + positive_numbers
print(integers) # [-1, -1, -1, -1, -1, 2, 3, 4, 5]
fruits = ['banana'.'orange'.'mango'.'lemon']
vegetables = ['Tomato'.'Potato'.'Cabbage'.'Onion'.'Carrot']
fruits_and_vegetables = fruits + vegetables
print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Copy the code
- The extend() method is concatenated with the extend() method to allow lists to be appended to lists. See the example below.
# grammar
list1 = [ 'item1' , 'item2' ]
list2 = [ 'item3' , 'item4' , 'item5' ]
list1.extend(list2)
Copy the code
num1 = [ 0 , 1 , 2 , 3 ]
num2 = [ 4 , 5 , 6] num1. extend ( num2 )print ( 'Numbers:' , num1 ) # Numbers: [0, 1, 2, 3, 4, 5, 6]
negative_numbers = [ - 5 , - 4 , - 3 , - 2 , - 1 ]
positive_numbers =[ 1 , 2 , 3 , 4 , 5 ]
zero = [ 0 ]
negative_numbers.extend(zero)
negative_numbers.extend(positive_numbers)
print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
fruits = ['banana'.'orange'.'mango'.'lemon']
vegetables = ['Tomato'.'Potato'.'Cabbage'.'Onion'.'Carrot']
fruits.extend(vegetables)
print('Fruits and vegetables:', fruits ) # of fruits and vegetables: [' banana ', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'have']
Copy the code
Evaluates the items in the list
The count () method returns the number of times the item is displayed in the list:
# grammar
lst = [ 'item1' , 'item2' ]
lst.count(item)
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon']
print(fruits.count('orange')) # 1
ages = [22.19.24.25.26.24.25.24]
print(ages.count(24)) # 3
Copy the code
Find the index of the item
The index () method returns the index of the item in the list:
# grammar
lst = [ 'item1' , 'item2' ]
lst.index(item)
Copy the code
Fruits = [ 'banana' , 'orange' , 'mango' , 'lemon' ]
print ( fruits . index ( 'orange' )) # 1
ages = [ 22 , 19 , 24 , 25 , 26 , 24 , 25 , 24 ]
print(ages.index(24)) #2, for the first timeCopy the code
Inversion of the list
The reverse () method will reverse the order of the list.
# grammar
lst = [ 'item1' , 'item2' ]
lst.reverse()
Copy the code
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits.reverse()
print(fruits) # ['lemon', 'mango', 'orange', 'banana']
ages = [22.19.24.25.26.24.25.24]
ages.reverse()
print(ages) # [24, 25, 24, 26, 25, 24, 19, 22]
Copy the code
Sort list item
To sort a list, we can use either the sort() method or the sorted() built-in function, which resorts the ascending list items and modifies the original list so that if reverse of sort() is equal to true, it sorts the list in descending order.
- Sort () : This method modifies the original list
# grammar
lst = [ 'item1' , 'item2' ]
lst . sort () # ascending
lst . sort ( reverse = True ) # descending
Copy the code
Example:
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits.sort()
print(fruits) # in alphabetical order, ['banana', 'lemon', 'mango', 'orange']
fruits.sort(reverse=True)
print(fruits) # ['orange', 'mango', 'lemon', 'banana']
ages = [22.19.24.25.26.24.25.24]
ages.sort()
print(ages) # [19, 22, 24, 24, 24, 25, 25, 26]
ages.sort(reverse=True)
print(ages) # [26, 25, 25, 24, 24, 24, 22, 19]
Copy the code
- Sorted () : Returns an ordered list without modifying the original list example:
fruits = ['banana'.'orange'.'mango'.'lemon']
print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange']
# Reverse order
fruits = ['banana'.'orange'.'mango'.'lemon']
fruits = sorted(fruits,reverse=True)
print(fruits) # ['orange', 'mango', 'lemon', 'banana']
Copy the code
If you have any help in learning Python, please bookmark it. Learn more about Python learning experience, tool installation package, ebook sharing, email me, follow me and keep updating.