Python Lists - List Type Tutorial with Examples - APPFICIAL

Veröffentlicht am: 08 September 2021
auf dem Kanal: Appficial
647
6

A container is a group of related object, with references to each object rather than directly to the data. One of the most common types of containers is a list, which is similar to a grocery shopping list. Ex: shopping_list = [‘chicken’, ‘beer’, ‘nachos’]. Each item in the list is called an element. Each element in the list is numbered starting at 0, so chicken is the object at index 0, beer is at index 1 and nachos are at index 2. You can access any element in the list by referencing the index number in square brackets. Ex: print(shopping_list[1]) will print out the string ‘beer’.

Lists can hold objects of any type. They are useful for reducing the number of variables need in your program. For example, if you wanted to store the temperatures for every day of the week, instead of having 7 separate variables like temp1, temp2, temp3 and so on, you can just have a list called temps, and access each day of the week by the index. For example:

temps = [85, 86, 90, 92, 88, 84, 79]
print(‘The temperature on Monday is’, temps[1]) # prints out 86


Accessing list elements

Here is a list of integers.

exam_scores = [84, 95, 39].

If you retook the exam you got a 39 on, and wanted to change it’s value, just access it by the index and reassign it. Ex:

print(’You failed Exam 3, your score was’, exam_scores[2])
exam_scores[2] = 100
print(’You aced Exam 3, your score is now’, exam_scores[2])

Updating list elements

Lists are mutable, which means that functions may alter or update elements in a list. You would need to reassign a list element in order to update it’s value.

Adding and removing list elements

A method is code that performs a specific action, and is called using dot notation. The append() method adds new elements to a list. Ex.

exam_scores.append(100)

Other useful methods for lists are pop() which removes an element at a specified index, and remove() which removes an element with the first matching value.

names = [‘Bob’, “Tony’, ‘Mary, ‘Joseph’, ‘Mary’]
names.pop(0) #removes Bob
names.remove(‘Mary’) #removes the first Mary from the list

There are a few useful built-in sequence-type operations that you can use when working with lists.

Subscribe to Appficial for more programming videos coming soon. Also, don't forget to click LIKE and comment on the video if it helped you out!


Auf dieser Seite können Sie das Online-Video Python Lists - List Type Tutorial with Examples - APPFICIAL mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Appficial 08 September 2021 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 647 Mal angesehen und es wurde von 6 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!