A Python list is a versatile data structure that allows you to group and store multiple items. Here are the key points about lists:
- Creating a List:
- You create a list by placing elements inside square brackets
[]
, separated by commas. - For example:
- You create a list by placing elements inside square brackets
ages = [19, 26, 29]
print(ages) # Output: [19, 26, 29]
2. List Characteristics:
- Ordered: Lists maintain the order of elements.
- Mutable: You can change items after creation.
- Allows duplicates: Lists can contain duplicate values.
3. Accessing List Elements:
- Each element in a list has an associated index (starting from 0).
- You can access elements using these index numbers.
- Example:
languages = ['Python', 'Swift', 'C++']
print(languages[0]) # Output: Python
print(languages[2]) # Output: C++
4. Adding Elements:
- Use the
append()
method to add an element to the end of a list. - Example:
fruits = ['apple', 'banana', 'orange']
fruits.append('cherry')
print(fruits) # Output: ['apple', 'banana', 'orange', 'cherry']